如何每6秒更改一次图像

How do I change images every 6 seconds?

本文关键字:一次 图像 何每 6秒      更新时间:2023-09-26

如何在下面的代码中添加一个间隔,使其每6秒自动更改一次图像?

我使用fearlessflyer.com中的代码

$(window).load(function () {
    var theImage = $('ul li img');
    var theWidth = theImage.width();
    //wrap into mother div
    $('ul').wrap('<div id="mother" />');
    //assign height width and overflow hidden to mother
    $('#mother').css({
        width: function () {
            return theWidth;
        },
        height: function () {
            return theImage.height();
        },
        position: 'relative',
        overflow: 'hidden'
    });
    //get total of image sizes and set as width for ul 
    var totalWidth = theImage.length * theWidth;
    $('ul').css({
        width: function () {
            return totalWidth;
        }
    });
    $(theImage).each(function (intIndex) {
        $(this).nextAll('a')
            .bind("click", function () {
            if ($(this).is(".next")) {
                $(this).parent('li').parent('ul').animate({
                    "margin-left": (-(intIndex + 1) * theWidth)
                }, 1000)
            } else if ($(this).is(".previous")) {
                $(this).parent('li').parent('ul').animate({
                    "margin-left": (-(intIndex - 1) * theWidth)
                }, 1000)
            } else if ($(this).is(".startover")) {
                $(this).parent('li').parent('ul').animate({
                    "margin-left": (0)
                }, 1000)
            }
        }); //close .bind()                                   
    }); //close .each()                      
}); //doc ready

这是一个扩展答案

var intNum = 6000; //repeat every 6 seconds
function startInterval(){
    window.int = setInterval(function(){
        //code to move to next image
    },intNum);
}

这将设置图像的间隔,自动进入下一个,与开关的点击事件相比,可能需要进行小的调整,所以我将内部留空。

当您知道代码的其余部分已经加载并准备就绪(点击事件已设置等)时,应该调用函数startInterval()。

当您进行点击事件以手动来回切换时,您希望使用以下

clearInterval(int);
//code to switch image from click
startInterval();

您需要使用setInterval()函数。

基本上,它看起来像:

var currentImg=0;//Current image tracker
var imgList["img1.jpg","img2.jpg","img3.jpg"];//Image names
var changeImage = function(){
     //Change src attribute on img element
     $('ul li img').attr('src','/imgdir/'+imgList[currentImg]);
     if(currentImg>=imgList.length-1)//Check if current image is the last in the list
         currentImg=0;//Sets to first images if true
     else
         currentImg++;//Sets to next image if false
}
//Sets an interval of 6000ms on the window object that calls the function changeImage()
//on every trigger
window.setInterval(changeImage(),6000);

MDN参考

希望这有帮助,我建议查看jQuery文档以及。。。

使用setInterval()javascript函数,如下所述。