2011-11-04 45 views
0

如何創建兩個滾動瀏覽器到文章標題的按鈕(「next」和「prev」)?動畫滾動到下一個/上一個帖子

<div id="cycle-posts"> 
    <a id="next" href="#next"></a> 
    <a id="prev" href="#prev"></a> 
</div> 

<article>My first post</article> 
<article>My second post</article> 
<article>My third post</article> 
<article>My fourth post</article> 

如果它是相關的:在前幾個之後,我的文章使用「無限滾動」加載。

這是我走到這一步,但它甚至還沒有接近:

$('#cycle-posts a').bind('click', function (e) { 
    $articles = $('article'); 
    e.preventDefault(); 
    var totalArticles = $articles.length; 


    if ($(this).attr("id") == "next") { 
     new_index = ++current_index; 
    } else if ($(this).attr("id") == "prev") { 
     new_index = --current_index; 
    } 

    if (new_index > totalArticles) { 
     new_index = 0; 
    } 

    $articles.removeClass('current').eq(new_index).addClass('current'); 

    console.log(new_index+'/'+totalArticles); 

    // now scroll offset, find offset based on .current? 

}); 

回答

1

在處理我們消除了current類,它實際上有它,然後我們選擇下一個(或前一個)元素和元素我們添加current類(僅當它不是第一個或最後一個元素時)。

然後我們滾動到該元素,動畫scrollTop,如here所述。

(function() { 
    var scrollTo = function(element) { 
     $('html, body').animate({ 
      scrollTop: element.offset().top 
     }, 500); 
    } 
    $('#next').click(function(event) { 
     event.preventDefault(); 
     var $current = $('#container > .current'); 
     if ($current.index() != $('#container > div').length - 1) { 
      $current.removeClass('current').next().addClass('current'); 
      scrollTo($current.next()); 
     } 
    }); 
    $('#prev').click(function(event) { 
     event.preventDefault(); 
     var $current = $('#container > .current'); 
     if (!$current.index() == 0) { 
      $current.removeClass('current').prev().addClass('current'); 
      scrollTo($current.prev()); 
     } 
    }); 
})(); 

You have a fiddle here

0

而不是試圖計算出每一次點擊當前索引,我覺得這是更好的使用功能,同時生產前向和後退單擊處理程序也將索引存儲爲本地。這樣既可以引用索引,也不需要即時計算。

請嘗試以下

(function() { 
    var index = 0; 
    $('article:first').addClass('current'); 
    var moveOne = function (forward) { 
    var articles = $('article'); 
    articles.eq(index).removeClass('current'); 
    if (forward) { 
     index++; 
     if (index === articles.length) { 
     index = 0; 
     } 
    } else { 
     index--; 
     if (index < 0) { 
     index = articles.length - 1; 
     } 
    } 
    articles.eq(index).addClass('current'); 
    } 

    $('#next').click(function() { moveOne(true); }); 
    $('#prev').click(function() { moveOne(false); }); 

})(); 

小提琴:http://jsfiddle.net/5f74F/

相關問題