2015-09-24 41 views
3

在我目前的解決方案從一個div滾動到另一個div我支持previousnext滾動到下一個div點擊,從當前位置

這可以通過保存上次滾動的div的索引來確定滾動到下一個的位置。然而,當用戶使用他們的輪子滾動時這會中斷我想知道是否有一種方法可以計算哪個div距窗口頂部最近,然後確定要滾動到下一個的索引。

這反過來會消除我遇到的問題。使用我目前的解決方案

測試錯誤:


  1. 轉到的jsfiddle鏈接
  2. 點擊向下箭頭兩次。它應該從一個div滾動到下一個div。
  3. 接下來,使用鼠標滾輪向下滾動頁面的3/4。
  4. 現在再次點擊向下箭頭。你會看到它會讓你回到你最後離開的頂部。

http://jsfiddle.net/JokerMartini/yj9pvz2a/1/

var curr_el_index = 0; 
var els_length = $(".section").length; 

    $('.btnNext').click(function() { 
     curr_el_index++; 
     if (curr_el_index >= els_length) curr_el_index = 0; 
     $("html, body").animate({ 
      scrollTop: $(".section").eq(curr_el_index).offset().top - 20 
     }, 700); 
    }); 

    $('.btnPrev').click(function() { 
     curr_el_index--; 
     if (curr_el_index < 0) curr_el_index = els_length - 1; 
     $("html, body").animate({ 
      scrollTop: $(".section").eq(curr_el_index).offset().top - 20 
     }, 700); 
    }); 

解決方案更新時間:http://jsfiddle.net/JokerMartini/82wo9e3c/1/

回答

0

嘗試添加該處理的頁面滾動。演示:http://jsfiddle.net/yj9pvz2a/2/

var section_height = $(".section").height() + 80; //80 margins 

$(window).on('scroll', function() { 
    curr_el_index = Math.floor($(window).scrollTop()/section_height); 
}); 

解釋:那您遇到在你的代碼是當用戶使用犯規您的導航滾動到不同的路段,curr_el_index保持不變。此$(window).scroll()功能不考慮您的導航按鈕的滾動。

功能:按鈕滾動時,它取窗口的滾動高度,並將其除以該部分的滾動高度,並將其舍入到最接近的整數,並將當前索引部分設置爲該數字。

+0

如果您一次滾動多個div元素,這可能會失敗。 – Aditya

+0

@Aditya,怎麼樣? – indubitablee

+0

剛剛從A滾動到J,然後單擊向上箭頭。跳過我,直接去了H.但這個解決方案几乎可以在所有情況下工作。 – Aditya

1

您可以使用jquery偏移量(http://api.jquery.com/offset/)檢索元素相對於文檔的當前偏移量。所以,你可以使用這樣的事情:

function getTopElement(elements){ 
    var topEl; 
    $.each(elements, function(index,el){ 
    if(!topEl || topEl.offset().top < el.offset().top){ 
     topEl = el; 
    } 
}); 

    return topEl; 
} 
+0

這將如何實現現有的代碼? – JokerMartini

1

this answer, 有一種方法,從視口的頂部計算DIV的距離,具體是這樣的:

($element.offset().top - $(window).scrollTop()) 

所以,你只需要找到一個最小的正值:

var closest_to_top = $('.section').toArray().reduce(function(curr, section) { 
    var bottom = $(section).offset().top + $(section).height() 
    var distance = (bottom - $(window).scrollTop()) 
    if (distance < 0) return curr 
    return distance > curr.distance ? curr : { 
     distance : distance, 
     section : section 
    } 
}, {section:null, distance:+Infinity}).section 

這是最高的部分,其底部低於頂部視。如果需要部分頂部,請移除+$(section).height()

相關問題