2013-06-28 26 views
0

如何将间隔添加到下面的代码中,以便它每6秒自动更改一次图像?如何每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 
+0

您是否在寻找类似事端[这个(http://jsbin.com/ewupey/1)? –

+0

我真的推荐使用[jQuery Cycle](http://malsup.com/jquery/cycle/)。 – prodigitalson

回答

0

使用setInterval()JavaScript函数,如解释here

+3

请不要参考w3school(因为http://www.w3fools.com) –

+1

好吧,不知道有关w2schools的问题。我改变了参考mozilla的文档。 – foobarbecue

+0

对不起,我不明白代码应该添加到哪里?帮助 –

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(); 
+0

我尝试了 –

+0

中的代码,我试着从开始到结束尝试粘贴代码,并没有奏效。或者我应该粘贴什么“//代码移动到下一张图片”?不能在那里调用函数“.bind(”点击“,函数(){”或其他东西添加inbetween? –

+0

基本上你想调整你的代码运行,就好像你点击“下一步”在那里。调用函数“startInterval()”在某处执行此操作 –

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 Reference

希望这有助于我建议检查出jQuery Documentation藏汉...

相关问题