Javascript图像更改onClick

时间:2015-10-11 22:13:38

标签: javascript image onclick

我创建的图片随点击而变化。我的代码没有用它做错了吗?

<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>

1 个答案:

答案 0 :(得分:0)

指定尺寸时需要一个单位:

_img.style.width = "1920px";
_img.style.height = "1280px";

当您使用6进行索引换行时,它应该是5。更好的是,使用数组的长度,如果数组发生更改,您就不需要更改代码的这一部分:

if(imgIdx > fNames.length) {
    imgIdx = 0;
}