我需要在每次点击时在两个图像之间切换我的元素背景图像。
我有这个,它只需切换颜色两次=\
<html>
<head>
<title>Javascript Change Div Background Image</title>
<style type="text/css">
#div1 {
width:100px;
height:30px;
background-image:url(blue.png);
}
</style>
<script language="javascript" type="text/javascript">
function changeDivImage() {
var imgPath = new String();
imgPath = document.getElementById("div1").style.backgroundImage;
if (imgPath == "url(blue.png)" || imgPath == "") {
document.getElementById("div1").style.backgroundImage = "url(green.png)";
}
else {
document.getElementById("div1").style.backgroundImage = "url(blue.png)";
}
}
</script>
</head>
<body>
<center>
<p>
This Javascript Example will change the background image of<br />
HTML Div Tag onclick event.
</p>
<div id="div1">
</div>
<br />
<input type="button" value="Change Background Image" onclick="changeDivImage()" />
</center>
</body>
</html>
最佳答案
某些浏览器可能会为您提供图像的绝对路径,而不是您提供的相对路径。
测试 URL 的 indexOf()
位置,而不是 ==
。
示例: http://jsfiddle.net/7Rp2G/2/ (点击按钮几次即可看到网址变化)
function changeDivImage() {
var imgPath = new String();
var div = document.getElementById("div1");
imgPath = div.style.backgroundImage;
div.style.backgroundImage = (imgPath.indexOf("blue.png") > -1 || imgPath == "")
? "url(green.png)"
: "url(blue.png)";
}
编辑:更新为用三元组替换 if()
。
关于javascript - JS元素样式切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3798616/