2013-02-11 88 views
-1

我有一个运作良好的div滑块:http://jsfiddle.net/UqSFr/2/Div滑块。加入5秒计时器,自动幻灯片

的基本功能是这样的:

$("#NextButton").click(function(e) { 
e.preventDefault(); 
if ($("#h_wrapper").is(':not(:animated)') && $("#NextButton").is(':not(:animated)')) { 
    var newMargin = CurrentMargin() - SlideWidth; 
    $("#h_wrapper").animate({ marginLeft: newMargin }, SlideSpeed, function() { SetNavigationDisplay() }); 
} 
}); 

除了点击的功能,我想添加一个计时器所以如果没有在5秒内点击,它应该移动到下一个。

定时器应点击重置

当达到最终它必须到第一个div(marginLeft = 0)

回答

2

看一看这段代码

$(document).ready(function(e) { 
    var index = 0; 
    var count = $('#h_wrapper').children().length; // set this value dynamically 

    var interval = setInterval(next, 1000); // create the interval 

    // move to next slide 
    function next() { 
     index = (index + 1) % count; 
     goto(index); 
    } 

    // move to previous slide 
    function previous() { 
     index = (index + count - 1) % count; // not too pretty, but it works 
     goto(index); 
    } 

    // go to slide x 
    function goto(x) { 
     var margin = index * SlideWidth; // set offset by index + width 

     $('#h_wrapper').stop().animate({ // stop cancels any running animations 
      'margin-left': margin 
     }, SlideSpeed, function(e) { 
      SetNavigationDisplay(); 
     }); 
    } 

    // set click handlers 
    $("#NextButton").click(next); 
    $("#PreviousButton").click(previous); 
}); 

这是挺容易。通过保存索引,更容易计算下一个和上一个偏移量。将整个动画分成单独的函数,代码不会变得更容易阅读和理解,但更容易调用。

+0

好的工作:D必须编辑一点点:var margin = - (index * Slidewidth);现在我只需要停止/取消定时器onMouseOver – 2013-02-11 12:12:02

+0

这里是工作版本,如果有人想复制和粘贴。 http://jsfiddle.net/UqSFr/9/ – 2013-06-27 05:12:25

+2

你应该避免命名你的函数goto,因为它是保留的。 – davidcondrey 2014-11-13 04:25:36