如何在滑块上制作时间间隔?

时间:2016-05-03 16:26:08

标签: jquery html

我的侧边栏

我在这里有一些divul列表

<div class="slider">
    <ul>
        <li><img src="http://127.0.0.1/anim/wp-content/uploads/2016/slider/cat1.jpg" alt=""></li>
        <li><img src="http://127.0.0.1/anim/wp-content/uploads/2016/slider/cat2.jpg" alt=""></li>
        <li><img src="http://127.0.0.1/anim/wp-content/uploads/2016/slider/cat3.jpg" alt=""></li>
    </ul>
</div>

和jQuery一样,这个滑块只有在点击后才能工作,但我需要在点击后和5秒间隔之后才能解决它?

$(document).ready(function() {
    $(".slider").each(function () { 
        var obj = $(this);
        $(obj).append("<div class='nav'></div>");
        $(obj).find("li").each(function () {
            $(obj).find(".nav").append("<span rel='"+$(this).index()+"'></span>"); 
            $(this).addClass("slider"+$(this).index());
        });
        $(obj).find("span").first().addClass("on"); 
    });
});

function sliderJS (obj, sl) { // slider function
    var ul = $(sl).find("ul"); 
    var bl = $(sl).find("li.slider"+obj); 
    var step = $(bl).width(); 
    $(ul).animate({marginLeft: "-"+step*obj}, 500); 
}

$(document).on("click", ".slider .nav span", function() { // slider click navigate
    var sl = $(this).closest(".slider"); 
    $(sl).find("span").removeClass("on"); 
    $(this).addClass("on"); 
    var obj = $(this).attr("rel"); 
    sliderJS(obj, sl); 
    return false;
});

如何每隔5秒制作一次间隔?

1 个答案:

答案 0 :(得分:2)

autoplayInterval = setInterval( moveToNext, 5000 );

function moveToNext()
{
  var curIndex = parseInt( $(".slider .nav span.on").attr("rel") );
  var totalSlides = $(".slider .nav span").length;
  var nextIndex = curIndex + 1;

  if( nextIndex >= totalSlides )
  {
    nextIndex = 0;
  }//if

  $(".slider .nav span.on").removeClass("on");
  $(".slider .nav span").eq( nextIndex ).addClass("on").trigger("click");

}//moveToNext();