I have an element on a page with background image set using css:
// CSS snippet
.mystyle {
background-image: url(some_image.gif);
// and other styles like width, height, padding, text-align, etc.
}
// HTML snippet
<input type="button" name="mybutton" id="b1" class="mystyle" onclick="
some_function();" value="Apply">
In a Javascript function, I'm trying to do the following:
newImage = "url(new_image.gif)";
document.getElementById( "b1" ).style.backgroundImage = newImage;
This does not work and the old background image disappears.
Moreover, when I check (using alerts) what the backgroundImage property was set to before and after I changed it:
newImage = "url(new_image.gif)";
alert( document.getElementById( "b1" ).style.backgroundImage );
document.getElementById( "b1" ).style.backgroundImage = newImage;
alert( document.getElementById( "b1" ).style.backgroundImage );
The first alert shows blank (empty string) and the second alert shows the newImage url.
So there is definitely something weird going on here. I'm just not sure what. Can anyone help?
EDIT: If, however, I only change the backgroundColor attribute and set the backgroundImage to 'none', the change seems to work jus开发者_如何转开发t fine (meaning, the backgroundImage disappears as before and i can see the new backgroundColor.
document.getElementById( "b1" ).style.backgroundImage = newImage;
When you set a backgroundImage
from script, the URL is relative to the page URL. If you set a background-image
from an external stylesheet, the URL is relative to the stylesheet. The difference may be causing your relative path to point to the wrong place. If you want to be certain, use rooted URLs.
The first alert shows blank (empty string)
That is expected. The style
property only reflects the contents of an element's inline style="..."
attribute, not any styles applied indirectly via stylesheet rules. You can get that information less reliably by looking at element.currentStyle
in IE or window.getComputedStyle
in other browsers. Or, better, use Firebug or the DOM inspector in Firefox to debug what rules are being applied.
Ok,
The first alert that appeared blank was because apparently (in IE) I need to do:
alert(document.getElementById( buttonMainId ).currentStyle.backgroundImage);
To change the background image I need to construct the full URL (http://blah/image.gif) in order for it to take effect.
精彩评论