var bg_img = curr_elem.style.backgroundImage || curr_elem.style.getAttribute("background-image");
如果curr_elem
在<style>
标记中设置了此属性而不是这样,则返回null:元素本身中的style = "background-image: url(blah.png);"
。
那么,我怎么知道代码中是否有一些背景图像应用于这个元素?
我们可以在IE9 +中使用getComputedStyle,但我需要这个用于IE6 +
<html>
<head>
<title>test clone elements</title>
<style type ="text/css">
#banner-map-225 .banner-map
{
background-image: url(test_bg.jpg);
}
</style>
</head>
<body>
<div id = "banner-map-225" ></div>
<div id = "inline_styled_div" style = "background-image: url(test_bg.jpg);" ></div>
<input type = "button" value = "test first div" onclick = "alert(document.getElementById('banner-map-225').style.backgroundImage);" />
<input type = "button" value = "test second div" onclick = "alert(document.getElementById('inline_styled_div').style.backgroundImage);" />
</body>
</html>
答案 0 :(得分:1)
有点好,但它应该有用......
var theDiv = document.getElementById('banner-map-225');
var styleArr = document.getElementsByTagName('STYLE');
var startPos;
var endPos;
var textFromStyle;
var theImageText;
for (var i = 0; i < styleArr.length; i++) {
// find the element selector
if (styleArr[i].innerHTML.toUpperCase().indexOf(theDiv.id) === -1) {
// use class name
startPos = styleArr[i].innerHTML.toUpperCase().indexOf(theDiv.className.toUpperCase());
if (startPos > -1) {
startPos = startPos + theDiv.className.length;
}
} else {
// use id
startPos = styleArr[i].innerHTML.toUpperCase().indexOf(theDiv.id.toUpperCase());
if (startPos > -1) {
startPos = startPos + theDiv.id.length;
}
}
if (startPos > -1) {
// get everything after selector
textFromStyle = styleArr[i].innerHTML.substring(startPos);
// find the style def for the element
startPos = textFromStyle.indexOf('{');
endPos = textFromStyle.indexOf('}');
if (startPos > -1) {
textFromStyle = textFromStyle.substring(startPos, endPos + 1);
// find bg image def
startPos = textFromStyle.toUpperCase().indexOf('BACKGROUND-IMAGE');
endPos = textFromStyle.indexOf(')');
if (startPos > -1) {
// get contents of url
startPos = startPos + ('BACKGROUND-IMAGE').length;
textFromStyle = textFromStyle.substring(startPos, endPos + 1);
startPos = textFromStyle.toUpperCase().indexOf('URL(') + ('URL(').length;
endPos = textFromStyle.indexOf(')');
if (startPos > -1) {
theImageText = trimString(textFromStyle.substring(startPos, endPos));
break;
}
}
}
}
}
// here's your image
if (theImageText) {
alert(theImageText);
}
// no trim in early IE
function trimString(sText) {
return sText.replace(/^\s+|\s+$/g, '');
}