簡體   English   中英

使用按鈕修復滾動到下一個div

[英]Fix for Scroll to the next div with buttons

因此,我有了這段代碼該代碼使我可以使用上一個下一個按鈕在div之間滾動,盡管我試圖找到一種方法來解決一個小問題,即當我使用鼠標滾輪或滾動條正常滾動時,該腳本仍然運行良好。然后返回以使用按鈕滾動,按鈕將頁面滾動到我以前使用按鈕滾動的位置,而我希望這可以繼續到我所在的位置,例如,如果我用鼠標滾輪滾動到div nr.3,當我單擊下一步按鈕時,我希望它繼續滾動到div nr.4。 也許通過創建:visible語句或其他方法可以完成工作,但是我不知道如何編寫。 這是代碼

$('div.postSection').first();

$('a.display').on('click', function(e) {
    e.preventDefault();

      var t = $(this).attr('id'),
      that = $(this);

    if (t === 'nextButton' && $('.currentPost').next('div.postSection').length > 0) {
        var $next = $('.currentPost').next('.postSection');
        var top = $next.offset().top;

        $('.currentPost').removeClass('currentPost');     
        $(function () {
               $next.addClass('currentPost');
               $('html, body').animate({scrollTop: $('.currentPost').offset().top-55 }, 'slow');

        });
  } else if (t === 'prevButton' && $('.currentPost').prev('div.postSection').length > 0) {
        var $prev = $('.currentPost').prev('.postSection');
        var top = $prev.offset().top;

        $('.currentPost').removeClass('currentPost');

        $(function () {
               $prev.addClass('currentPost');
               $('html, body').animate({scrollTop: $('.currentPost').offset().top-55 }, 'slow');
        });
  } 
});

您可以監視每個項目的滾動,並使用class或data屬性標記它們,以跟蹤可見或不可見的內容。

或者,我剛剛發現的是一個不錯的選擇器擴展,用於在可見區域(視口-如此命名)中獲取項目。 只需根據“下一步”或“上一步”單擊獲取first()或last()即可使用它。

視口: http : //www.appelsiini.net/projects/viewport

擴展的工作方式如下:

$currentPS = $('.postSection:in-viewport').first();

然后,您只需要更新下一個和上一個:

var $next = $currentPS.next('.postSection');

var $prev = $currentPS.prev('.postSection');

似乎工作得很好: http : //jsfiddle.net/j7e9cogs/2/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM