jQuery选择滑块中的列表项

时间:2015-08-04 15:53:45

标签: jquery

熙!

我正在构建一个简单的滑块,现在它的工作完美只有现在我还要提供类名如slider1,slider2 enz

如果(sliderNumber == 7){

,这部分看起来也很愚蠢

我想知道如何改进我的代码以使其更具响应性

        $(document).ready(function () {
      fadeSlider();
  });

  function fadeSlider() {
      sliderNumber = 1;
      $('.slide' + sliderNumber).addClass('active');
      fader();

      function fader() {
          if (sliderNumber == 7) {
              setTimeout(function () {
                  $('.slide' + sliderNumber).removeClass('active');
                  sliderNumber = 1;
                  $('.slide' + sliderNumber).addClass('active');
                  fader();
              }, 1000);
          } else {
              setTimeout(function () {
                  $('.slide' + sliderNumber).removeClass('active');
                  sliderNumber++;
                  $('.slide' + sliderNumber).addClass('active');
                  fader();
              }, 1000);
          }
      }
  }

Html

<ul class="totalSlider">
              <li class="totalRaised slide1">a</li>
              <li class="totalRaised slide2">b</li>
              <li class="totalRaised slide3">c</li>
              <li class="totalRaised slide4">d</li>
              <li class="totalRaised slide5">e</li>
              <li class="totalRaised slide6">f</li>
              <li class="totalRaised slide7">g</li>
</ul>

CSS

.totalSlider li{
  display: none;
  list-style: none;
}
.totalSlider li.active{
  display: inline-block;
}

和jsfiddle:https://jsfiddle.net/x7xk3295/

1 个答案:

答案 0 :(得分:2)

您可以使用以下逻辑,切换活动类:

$(fadeSlider);

function fadeSlider() {
    setInterval(function () { // use an interval if you want code to be called in loop
        var $next = $('.active').next().length ? $('.active').next() : $('.totalRaised:first-child'); //'next' element would be: if there is an element following current active one, the next one, otherwise, the first child
        $('.active').add($next).toggleClass('active');// toggle active class for the active one and the next one
    }, 1000);
}

-jsFiddle-