0

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

我使用来自无畏飞行器的这段代码

$(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
4

3 回答 3

1

这是一个扩展的答案

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();
于 2013-06-28T20:40:15.500 回答
1

您需要使用 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 文档...

于 2013-06-28T20:40:37.807 回答
0

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

于 2013-06-28T20:24:08.127 回答