2013-05-15 32 views
13

我有一個腳本可以計算頁面頂部元素列表的距離,但我不確定如何檢測它距離頁面的距離底端。當它擊中的底部(當然,前下方20像素)我想觸發一個事件,並淡出出來:使用jQuery來檢測元素何時接近頁面底部

$(window).on('load resize scroll', function() { 
    $('.links__item').each(function() { 
     if (($(this).offset().top - $(window).scrollTop()) < 20) { 
      $(this).stop().fadeTo(100, 0) 
     } else { 
      $(this).stop().fadeTo('fast', 1) 
     } 
    }) 
}) 

如果任何人有任何建議,大加讚賞。我遍歷元素來檢測它,所以當它們中的一個從底部打到20px時,我想淡出它。謝謝!

+0

這可能有助於底部:http://stackoverflow.com/a/3898152/1823841 –

回答

14

您可以在計算使用jQuery函數height(),如:

$(window).height(); 
$(this).height(); 

特別是,如果要檢測如果元素的頂部接近頁面的底部,你可以使用這個鈣:

if ($(this).offset().top > ($(window).scrollTop() + $(window).height() - 20)) // True 
4

太平,

我不知道你想火什麼,但你可以測試頁面的底部這樣

$(window).on('load resize scroll', function() { 
    $('.links__item').each(function() { 
     if(($(this).offset().top > ($(window).scrollTop() + $(window).height() - 20)) { 
      $(this).stop().fadeTo(100, 0) 
     } else { 
      $(this).stop().fadeTo('fast', 1) 
     } 
    }) 
}) 

原因是是jQuery的發現基於其高度的頁面

1 $(window).height(); // returns height of browser viewport 
2 $(document).height(); // returns height of HTML document 
+0

布魯諾了那裏,只是用更快相同的答案,但非常感謝你:)! – Halcyon991

相關問題