我不知道为什么,但我的Javascript只能在Firefox和IE中运行一次(但它在Chrome中运行良好)。有人知道为什么吗?
<script type="text/javascript">
function changeDivImage()
{
var imgPath = new String();
imgPath = document.getElementById("div1").style.backgroundImage;
if (imgPath == "url(images/1.jpg)" || imgPath == "")
{
document.getElementById("div1").style.backgroundImage ="url(images/2.jpg)";
}
else if (imgPath == "url(images/2.jpg)")
{
document.getElementById("div1").style.backgroundImage = "url(images/3.jpg)";
}
else if (imgPath == "url(images/3.jpg)")
{
document.getElementById("div1").style.backgroundImage = "url(images/1.jpg)";
}
}
</script>
点击图片
触发脚本<img src="images/leftarrow.png"
value="Change Background Image"
onclick="changeDivImage()" />
答案 0 :(得分:1)
浏览器倾向于以不同方式规范化CSS属性。例如,IE和Firefox在URL周围加上了引号。
所以,也许你应该试试这个:
var div = document.getElementById('div1'),
imgPath = parseInt(div.style.backgroundImage.match(/\d(?=\.jpg)/) || ["0"],10),
newnum = imgPath%3+1;
div.style.backgroundImage = "url(images/"+newnum+".jpg)";