JQuery - 使用计时器循环一个类 [英] JQuery - Cycle a class with timer

查看:81
本文介绍了JQuery - 使用计时器循环一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在结构下面有一个列表

I've a list wit below structure

<div id="slider">
  <ul>
    <li class='active'> a </li>
    <li> b </li>
    <li> c </li>    
    <li> d </li>
    <li> e </li>
  </ul>
</div>

我需要以自行车的方式更改li的类'active'
这是我正在使用的脚本。问题是要么将活动类添加到所有li中,要么从所有li中删除类活动

I need to change the class 'active' of li's in a cycling manner Here is the script I'm working with. issue is it either adds the class active to all li's or removes the class active from all li's

      toggleSlide = function(){
          $("#slider ul li").each(function(index) {
            if($(this).hasClass('active')){

              $("#slider ul li").removeClass('active');
              $(this).next().addClass('active'));
              //lis = $("#slider ul li")
              //$(lis[(index+1)%lis.length]).addClass('active');
            }
          });
        }
   setInterval(toggleSlide, 5000);​


推荐答案

您可以使用 .add() .last() 因为 .add() 按文档顺序转换,它看起来像这样:

You can greatly simplify this with .add() and .last() since elements from .add() are turned in document order, it would look like this:

var toggleSlide = function(){
  $("#slider li.active").removeClass()
   .next().add("#slider li:first").last().addClass("active");
}
setInterval(toggleSlide, 5000);

你可以在这里测试一下(演示的持续时间为1000毫秒)

这是如何工作的,需要下一个 < li> 如果有一个,那么也可以使用 .last() (因为它们按文档顺序排列)我们将获得 .next() 一个如果它在那里,否则该集只包含一个元素, :第一个 < li> ,我们回到了开头。

How this works is it takes the next <li> if there is one, then adds the first one as well, by using .last() (since they're in document order) we'll get the .next() one if it's there, otherwise the set only contains one element, the :first <li>, and we're back to the beginning.

这篇关于JQuery - 使用计时器循环一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆