Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

html - How can I determine the background image URL of a div via JavaScript?

I've found plenty of information on how to change the background image of a div using JavaScript, but I am trying to use JavaScript to determine which background image is being displayed. The code to set the image goes like this:

document.getElementById("widgetField").style.background="url(includes/images/datepicker_open.png)";

I have tried every combination I can think of to access the background image url, but so far no dice:

alert(document.getElementById("widgetField").style.backgroundImage.url);  - returns Undefined
alert(document.getElementById("widgetField").style.backgroundImage);  - empty response
alert(document.getElementById("widgetField").style.background);
alert(document.getElementById("widgetField").style.background.image);
alert(document.getElementById("widgetField").style.background.url);
alert(document.getElementById("widgetField").style.background.image.url);
alert(document.getElementById("widgetField").style.background.value);
alert(document.getElementById("widgetField").style.background.image.value);
alert(document.getElementById("widgetField").style.background.image.value);
alert(document.getElementById("widgetField").style.backgroundImage.value);

Does anyone know how to do this? Is it possible?

BTW, here is the way the image is being set in CSS in the beginning:

#widgetField {
    width: 290px;
    height: 26px;
    background: url(../images/datepicker_closed.png);
    overflow: hidden;
    position: relative;
}

UPDATE:

If I run the following, it works:

document.getElementById("widgetField").style.background="url(includes/images/datepicker_open.png)";
alert(document.getElementById("widgetField").style.background);

However, I cannot seem to access the URL property until it has been set by JavaScript, even though it is already defined in the CSS file. Is there a reason why the raw CSS setting is not accessible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

var img = document.getElementById('widgetField'),
style = img.currentStyle || window.getComputedStyle(img, false),
bi = style.backgroundImage.slice(4, -1);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...