2012-01-13 66 views
0

我寫了這個無限滾動旋轉木馬,我想知道做非無限滾動的最佳方式是什麼。製作旋轉木馬不是無限滾動

現在,用戶指定他們希望在視圖@一次(在numSlide中)出現多少個項目。所以基本上,用戶點擊右箭頭,它使用調用prevLoopnextLoop的.animate()方法。這些基本上只是拉取指定的元素的數量,並相應地將它們移動到<ul></ul>的開始或結束。

我已經到目前爲止,但現在我試圖介紹關閉無限滾動的選項(例如只顯示列表中的項目,一旦你到達每邊的結尾,它可以防止調用prevLoop/nextLoop。

我的想法是,基本上,設置一個名爲無限可變的。不管是哪種的點擊功能(rightClick()leftClick())檢查,看看是否無限是真的。如果是,使用正常的滾動碼,否則,我在考慮:在numElements中找到<ul>內的元素數量,設置一個計數變量以通過每次點擊增加,並檢查計數是否等於或小於numElements。如果是> numElements,那麼ID防止任何功能動畫更多。我覺得這很快就會變得很雜亂/忙碌。

這將會是設置這樣的:

var count = numElements; 
    function rightClick() { 
    var cfirst = container.find('li').first(), //the current first element 
     tomove = cfirst.nextLoop(numSlide - 1, true), //the elements that need to move 
     nfirst = tomove.last().nextLoop(1, false); //the new first element 

    /* 
     Pretend we currently have [A, B, C, D, E, F, G, H, I] and numSlide is 3 
     cfirst === [A] 
     tomove === [A, B, C] 
     nfirst === [D] 
    */ 

    var indent = cfirst.offset().left - nfirst.offset().left; 

    if (infinite) { 
    ul.not(':animated').animate({ // not:animated makes sure we only get one @ a time 
     'left': indent 
    }, 'fast', function() { 
     tomove.appendTo(ul); //Move them to the end of the UL 
     ul.css({ // left indent of ul 
      'left': 0 
     }); 
    }); 
} else { 
    // Infinite is turned off, handle it in here 
    count = count -1; 
    // Animate numElements - numSlide 
} 
} 

任何人有任何其他的想法?由於它是在這裏是一個工作演示:處理這種事情是保持在「最後」 <li>參考(因爲它是以前任何<li>小號被轉移),並使用.index()

http://jsfiddle.net/someprimetime/AYfhn/

回答

1

的一種方式找到其當前位置在<ul>,就像這樣:

var lastIndex = last.index(); 

if (infinite || (lastIndex + 1 >= rowSize + numSlide)) { 
    // animate 
} else if (lastIndex >= rowSize) { 
    // animate using smaller numSlide 
} else { 
    // don't animate 
} 

還有一兩件事:

你應該考慮把你的代碼放到一個jQuery plugin。他們很容易寫。你不需要分發它或任何東西;這只是爲了使它更容易使工作更容易。特別是,您將受益於options and defaults,並且您可以使用data method保留狀態(例如「最後」<li>)。

+0

謝謝!從我剛開始閱讀jQuery創作插件頁面開始,這段代碼就已經過時了。我也在考慮使用index()或eq()來跟蹤當前元素,所以謝謝! – 2012-01-13 17:51:43