js点击事件改变div背景图片怎么实现 5
functionlogo(){varbtn=document.getElementById("button_A");i=0;varimgArr=newArray(["im...
function logo() {
var btn = document.getElementById("button_A");
i=0;
var imgArr = new Array(["img/1.jpg", "img/2.jpg", "img/3.jpg", "img/4.jpg","img/5.jpg","img/6.jpg"]);
btn.addEventListener("click", function () {
i++;
document.getElementById("img_A").style.backgroundImage= "url(imgArr[i]) ";
});
}
这个得怎么改 展开
var btn = document.getElementById("button_A");
i=0;
var imgArr = new Array(["img/1.jpg", "img/2.jpg", "img/3.jpg", "img/4.jpg","img/5.jpg","img/6.jpg"]);
btn.addEventListener("click", function () {
i++;
document.getElementById("img_A").style.backgroundImage= "url(imgArr[i]) ";
});
}
这个得怎么改 展开
1个回答
展开全部
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button type="button" id="button_A">changeBackground</button>
<script type="text/javascript">
function logo() {
var btn = document.getElementById("button_A");
i = 0;
var imgArr = ["img/1.jpg", "img/2.jpg", "img/3.jpg", "img/4.jpg", "img/5.jpg", "img/6.jpg"];
btn.addEventListener("click", function () {
if (i == 6) {
i = 0;
}
document.body.style.backgroundImage = "url('"+imgArr[i]+"')";
i++;
});
}
logo();
</script>
</body>
</html>
用您的改进后的代码,js代码必须再按钮的标签后面(要不然需要再监听dom加载完毕后执行js),i不应该一直加下去,会出错!
参考:http://www.w3school.com.cn/jsref/prop_style_backgroundimage.asp
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询