2012-05-28 105 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