我需要在每次點擊它時切換我的元素背景圖像beetwin兩個圖像。JS元素樣式切換
我有這個,BYT它swithes顏色只是兩次= \
<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>
嘗試提醒'imgPath'來查看url(green.png)是否被解析爲圖像的完整url路徑,在這種情況下,if將會失敗..也檢查以查看(更可能)if瀏覽器會在url附加引號.. – 2010-09-26 16:16:35
爲什麼不使用CSS類? – 2010-09-26 20:16:10