javascript - 我的幻灯片只循环播放一张照片

标签 javascript jquery html css slideshow

我正在尝试使用 jQuery 设计幻灯片,我想出了下面的代码,但是,当我运行它时,它只循环播放一张幻灯片,然后停止做任何进一步的事情。如何让图片循环显示?

jQuery:

$(function() {
    setInterval("rotateImages()", 3000);
});
function rotateImages() {
    var CurrentPhoto = $('#slideshow .current');
    var NextPhoto = CurrentPhoto.next();
    if (NextPhoto.length == 0) {
        NextPhoto = $('#slideshow div:first');
    }  
    CurrentPhoto.removeClass('current').addClass('previous');
    NextPhoto.css({ opacity: 0.0 }).addClass('current')
         .animate({ opacity: 1.0 }, 1000,
    function() {
         CurrentPhoto.removeClass('previous');
    }
}

HTML:

                <div id="slideshow">          
            <div class="current"><img src="image1.jpg" alt="Img" height="382" width="594"> </div>
            <div><img src="image2.jpg" alt="Img" height="382" width="594">             </div>
            <div><img src="image3.jpg" alt="Img" height="382" width="594"></div>
            <div><img src="image4.jpg" alt="Img" height="382" width="594"></div>
            <div><img src="image5.jpg" alt="Img" height="382" width="594"></div>
            </div>

...

CSS:

#slideshow div {
    z-index: 0;
    position: absolute;
    margin: 0px 0px 0px 362px;
}
#slideshow div.previous {
    z-index: 1;
}
#slideshow div.current {
    z-index: 2;
}

最佳答案

脚本中有两个错误:

  1. 缺少用于关闭 animate 函数的括号(您可以在 JavaScript 控制台中轻松看到的内容)。
  2. NextPhoto == 0 不正确。您想检查 NextPhoto 的长度是否为 0,而不是 NextPhoto 本身。

解决这两件事,问题就解决了:

$(function() {
    setInterval("rotateImages()", 3000);
});
function rotateImages() {
    var CurrentPhoto = $('#slideshow .current');
    var NextPhoto = CurrentPhoto.next();
    if (NextPhoto.length == 0) {
        NextPhoto = $('#slideshow div:first');
    }  
    CurrentPhoto.removeClass('current').addClass('previous');
    NextPhoto.css({ opacity: 0.0 }).addClass('current')
             .animate({ opacity: 1.0 }, 
                      1000,
                      function() {
                          CurrentPhoto.removeClass('previous');
                      });
}

在这个 JSFiddle 上查看:http://jsfiddle.net/h7afu5ex/

关于javascript - 我的幻灯片只循环播放一张照片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31254328/

相关文章:

c# - 使用嵌套类创建类的 Javascript JSON

javascript - GSAP 重复交错循环

html - @keyframes 在 10 以下的 IE 中不起作用

javascript - 包含 "this"关键字的方法在另一个方法中调用时与分配给局部变量时的工作方式不同

javascript - 如何在文本区域中从右到左书写英文

javascript - 定位一个复选框并使用 Jquery 删除它

javascript - JS根据类型通过HTML ID标签搜索有限制吗?

javascript - 如果不需要执行操作,则创建延迟

javascript - 在 React 中正确渲染 HTML 标签

javascript - 在 bootstrap-vue 中渲染自定义样式