JavaScript幻灯片停留在第一张照片上

时间:2014-11-29 06:44:43

标签: javascript slideshow

我是一名Javascript初学者尝试使用Javascript制作简单的幻灯片。从我完成的工作中,我只能制作五幅图像中的一幅。控制台说没有错,我不知道为什么其他图片不会显示。

<script>
    var images = new Array();
        images[0] = new Image();
        images[0].src = "burger1.jpg";
        images[1] = new Image();
        images[1].src = "burger2.jpg";
        images[2] = new Image();
        images[2].src = "burger3.jpg";
        images[3] = new Image();
        images[3].src = "burger4.jpg";
        images[4] = new Image();
        images[4].src = "burger5.jpg";


    var slide = 0;

    function next(){
        if (!document.images) {
          return document.getElementById('slideshow').src = images[slide].src
        }       
        if(slide < 5){
          slide++;
        } else{
            slide = 0;
          }
      setTimeout("next()",3000);
    }

    next();

</script>
</head>

<body>
<img src="burger1.jpg" id="slideshow" width=100 height=100 />

P.S我不知道jquery。

3 个答案:

答案 0 :(得分:0)

删除

   if (!document.images) {
      return document.getElementById('slideshow').src = images[slide].src
    } 

添加

document.getElementById('slideshow').src = images[slide].src

setTimeout之后

答案 1 :(得分:0)

if (!document.images) {
      return document.getElementById('slideshow').src = images[slide].src
    } 

此处!document.images为[object HTMLCollection],您只检查此用途的!

if(slide < 5){
          slide++;
        } else{
            slide = 0;
          }
      setTimeout(next,3000);
document.getElementById('slideshow').src = images[slide].src

答案 2 :(得分:0)

还有更多要修复的代码,以便我尝试向您展示更好的方法,然后只是 quicky

<强> jsBin demo

var slideshow = document.getElementById('slideshow'), // Cache your element!
    images = [                            // Create an array of images paths
       "burger1.jpg", 
       "burger2.jpg",
       "burger3.jpg"
    ],
    slide = 0,
    tot = images.length;    // count the total of images

for(var i=0; i<tot; i++){   // preload images (so we don't have to wait for them)
  var img = new Image();
  img.src = images[i];
}


function next() {
  slideshow.src = images[slide++ % tot]; // Modulo operator to loop the counter
  setTimeout(next, 3000);                // Don't wrap `next` in String
}
next();