image arrays using JavaScript

不羁的心 提交于 2019-12-12 01:19:29

问题


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>


来源:https://stackoverflow.com/questions/13795994/image-arrays-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!