我创建的图片随点击而变化。我的代码没有用它做错了吗?
<div id="img"></div>
<script>
var fNames = ["SD1", "SD2", "SD3", "SD4"]; //File names
var _img = document.getElementById("img"); //Grabs images, groups them
var imgIdx = 0;
_img.style.position = "relative";
_img.style.left = "auto";
_img.style.right = "auto";
_img.style.width = "1920";
_img.style.height = "1280";
_img.style.backgroundImage = "url('images/"+fNames[imgIdx]+".jpg')"; //Retrieves images from file
_img.addEventListener("click", onImageClick); //Allows image click
function onImageClick() {
imgIdx++;
if(imgIdx == 6) {
imgIdx = 0;
}
_img.style.backgroundImage = "url('images/"+fNames[imgIdx]+".jpg')";
}
</script>
答案 0 :(得分:0)
指定尺寸时需要一个单位:
_img.style.width = "1920px";
_img.style.height = "1280px";
当您使用6
进行索引换行时,它应该是5
。更好的是,使用数组的长度,如果数组发生更改,您就不需要更改代码的这一部分:
if(imgIdx > fNames.length) {
imgIdx = 0;
}