简体   繁体   中英

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 . 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM