image arrays using JavaScript

2019-08-29 15:24发布

问题:

I need help creating image arrays using JavaScript. I need to create an array of images to cycle through using their src attribute to cycle through them. Then the images need to be cycled to the next and previous buttons. the images must loop through the cycle. In other words don’t have them end. when clicking next, once you hit the end of your images, they should just start back at the first image and repeat.

Could someone please write a simple code for this? I would really appreciate it.

回答1:

I was bored and I hadn't built one of these before. Here is what I came up with: http://jsfiddle.net/grantk/pHdAN/

<div id="images" style="height:300px;">
    <img src="http://www.livehacking.com/web/wp-content/uploads/2012/08/chrome-logo-1301044215-300x300.jpg" />
    <img src="http://upload.wikimedia.org/wikipedia/commons/e/e7/Mozilla_Firefox_3.5_logo_256.png" />
    <img src="http://html5doctor.com/wp-content/uploads/2011/01/HTML5_Logo_256.png" />
</div>
<a id="prev" href="#">Prev</a> <a id="next" href="#">Next</a>

<script>
var imgArr = document.getElementById('images').getElementsByTagName('img');

//Hide all images except first
for(var i=1; i<imgArr.length; i++){
    imgArr[i].style.display = "none";
}
i=0;

document.getElementById('prev').onclick = function(){
    if(i===0){
        imgArr[i].style.display = "none";
        i=imgArr.length-1;
        imgArr[i].style.display = "";
    }
    else{
        imgArr[i].style.display = "none";
        i--;
        imgArr[i].style.display = "";
    }
}

document.getElementById('next').onclick = function(){
    if(i===imgArr.length-1){
        imgArr[i].style.display = "none";
        i=0;
        imgArr[i].style.display = "";
    }
    else{
        imgArr[i].style.display = "none";
        i++;
        imgArr[i].style.display = "";
    }
}
</script>