【问题标题】:Making a Slideshow Delay Image Cycling Using JS & JQuery使用 JS 和 JQuery 制作幻灯片延迟图像循环
【发布时间】:2020-08-14 11:47:31
【问题描述】:

我正在尝试使用 JS 和 JQuery 创建小幻灯片。下面的代码可以工作(有点),但在显示下一张图片之前不会延迟;立即显示。在显示下一张图片之前,我试图让它延迟 5 秒。我是个新手,如果代码有问题,请见谅。

*已更改 URL 以使其更具可读性。

感谢您的帮助!

var backgroundImg = ["https://x1.jpg", "https://x2.jpg"];
var backgroundImgLength = backgroundImg.length;

var z = 0;

do {

        slideShow(backgroundImg[z]);
        z++;

}
while (z < backgroundImgLength);

function slideShow(url) {

    setTimeout(function() {
        
        $('.header-section').css('background-image', 'url(' + url + ')');

    }, 5000);        

}

【问题讨论】:

    标签: javascript jquery settimeout slideshow


    【解决方案1】:

    我会尝试以这种方式使用它:

    const backgroundImg = [
        "https://picsum.photos/id/237/200/300",
        "https://picsum.photos/id/239/200/300"
    ];
    const backgroundImgLength = backgroundImg.length;
    
    let backgroundImgIndex = 0;
    let backgroundImgUrl = backgroundImg[backgroundImgIndex];
    
    const changeImage = function() {
        $('.header-section').css('background-image', 'url(' + backgroundImgUrl + ')');
    }
    
    const getNextImgIndex = function() {
        return (backgroundImgIndex + 1 < backgroundImgLength) ? backgroundImgIndex + 1 : 0;
    }
    
    // setInterval allows us to run a function repeatedly,
    // starting after the interval of time,
    // then repeating continuously at that interval.
    const timerId = setInterval(function() {
        backgroundImgIndex = getNextImgIndex();
        backgroundImgUrl = backgroundImg[backgroundImgIndex];
      
        changeImage();
    }, 5000);
    
    changeImage();
    

    请看这里https://codepen.io/vyspiansky/pen/jOqqNmQ

    【讨论】:

    • 那真是太棒了。只是一个跟进。为什么你有这个 'const changeImage = function()' 而不仅仅是 'function changeImage() {}'?将函数分配给变量有什么需要?对不起菜鸟问题。 ://
    • 我猜,你可以在这个例子中互相替换。我没有特别的目的。只是习惯问题。你可以在这里阅读差异stackoverflow.com/questions/336859/…
    猜你喜欢
    • 2011-08-15
    • 2012-12-20
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 2012-09-13
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多