2012-05-28 58 views
1

我有以下的jQuery:向后循环播放幻灯片

  var $active = $('#slideshow li.active'); 

      if ($active.length == 0) $active = $('#slideshow li:last'); 

      // use this to pull the images in the order they appear in the markup 
      var $next = $active.next().length ? $active.next() 
       : $('#slideshow li:first'); 

      // uncomment the 3 lines below to pull the images in random order 

      // var $sibs = $active.siblings(); 
      // var rndNum = Math.floor(Math.random() * $sibs.length); 
      // var $next = $($sibs[ rndNum ]); 


      $active.addClass('last-active'); 

      $next.css({opacity: 0.0}) 
       .addClass('active') 
       .animate({opacity: 1.0}, 500, function() { 
        $active.removeClass('active last-active'); 
       }); 

如何修改,这样我可以循环倒退?

我已经到目前为止,但它不会循环回到第一个元素的最后一个元素。有一些东西很简单,我很想念,但我真的无法把它放在手上。

  var $active = $('#slideshow li.active'); 

      if ($active.length == 0){ $active = $('#slideshow li:last');} 

      // use this to pull the images in the order they appear in the markup 
      var $next = 0 ? $active.prev() 
       : $('#slideshow li:first'); 

      // uncomment the 3 lines below to pull the images in random order 

      // var $sibs = $active.siblings(); 
      // var rndNum = Math.floor(Math.random() * $sibs.length); 
      // var $next = $($sibs[ rndNum ]); 


      $active.addClass('last-active'); 

      $next.css({opacity: 0.0}) 
       .addClass('active') 
       .animate({opacity: 1.0}, 500, function() { 
        $active.removeClass('active last-active'); 
       }); 

回答

1

当前的解决方案检查元素后面是否有元素。我们将更改此项,以查看之前是否存在一个,active元素。原始回退是选择#slideshow内的第一个列表项。我们将选择最后一个。

var $next = $active.prev().length ? $active.prev() : $('#slideshow li:last'); 

如果你不熟悉的三元运算符,它本质上是同样的事情,如果语句写的:

// If there are previous elements 
if ($active.prev().length > 0) { 
    // The next element will be the previous element 
    $next = $active.prev(); 
} else { 
    // The next element will be the last list item in #slideshow 
    $next = $("#slideshow li:last"); 
} 
+0

@JohnathanSampson非常感谢你!我知道这是这样的,但我真的很努力阅读jQuery。我喜欢尝试将它解释为英文,但却一直在努力阅读代码的确切内容。 –

+0

如何准确读取 if($ active.prev()。length) ? 请问是否有长度? –

+0

@AntonioMoore“如果我们有以前的元素。” '.length'部分计数'.prev()'部分。所以这就像问“我们有多少.prev()”?如果没有,则'0'将是该值,并且这在JavaScript中被认为是* falsy *。 jQuery用'.prev()'返回1个元素,所以我们期望'.length'是'1'。如果不是,我们知道我们没有任何以前的元素。 – Sampson