Javascript 更改backgroundImage属性时遇到问题
我在使用css设置背景图像的页面上有一个元素:Javascript 更改backgroundImage属性时遇到问题,javascript,css,Javascript,Css,我在使用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" oncl
// 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">
这不起作用,旧的背景图像将消失
此外,当我检查(使用警报)backgroundImage属性在更改前后的设置时:
newImage = "url(new_image.gif)";
alert( document.getElementById( "b1" ).style.backgroundImage );
document.getElementById( "b1" ).style.backgroundImage = newImage;
alert( document.getElementById( "b1" ).style.backgroundImage );
第一个警报显示空白(空字符串),第二个警报显示newImage url
所以这里肯定发生了一些奇怪的事情。我只是不知道是什么。有人能帮忙吗
编辑:
但是,如果我只更改backgroundColor属性并将backgroundImage设置为“none”,则更改似乎效果很好(也就是说,backgroundImage会像以前一样消失,我可以看到新的backgroundColor)
document.getElementById(“b1”).style.backgroundImage=newImage
从脚本设置背景图像
时,URL与页面URL相对。如果从外部样式表设置背景图像
,URL与样式表相对。这种差异可能会导致相对路径指向错误的位置。如果要确定,请使用根URL
第一个警报显示空白(空字符串)
这是预期的。style
属性仅反映元素内联style=“…”的内容
属性,而不是通过样式表规则间接应用的任何样式。通过查看IE中的元素。currentStyle
或其他浏览器中的窗口。getComputedStyle
可以获得不太可靠的信息。或者,最好使用Firefox中的Firebug或DOM inspector来调试正在应用的规则。Ok
第一个出现空白的警报是因为(在IE中)我显然需要:
alert(document.getElementById( buttonMainId ).currentStyle.backgroundImage);
若要更改背景图像,我需要构造完整的URL(),以使其生效。您是否确保要加载的图像存在于给定路径?您的代码似乎正确。是的。请参阅下面的答案。我必须确保它是完整路径(非相对路径).我在下面贴出我的答案后看到了这一点。我通过反复试验找到了答案。不过非常感谢。
alert(document.getElementById( buttonMainId ).currentStyle.backgroundImage);