[英]Javascript Image change onClick
I'm creating an image that changes on click.我正在创建一个单击时更改的图像。 My code isn't working whats wrong with it?
我的代码不工作有什么问题吗?
<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>
You need a unit when you specify the size:指定大小时需要一个单位:
_img.style.width = "1920px";
_img.style.height = "1280px";
When making the index wrap around you are using 6
, but it should be 5
.当使索引环绕时,您使用的是
6
,但它应该是5
。 Better yet, use the length of the array, that way you don't need to change that part of the code if the array changes:更好的是,使用数组的长度,这样如果数组更改,您就不需要更改代码的那部分:
if(imgIdx > fNames.length) {
imgIdx = 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.