2010-05-12 118 views
18

我想確定何時滾動到頁面的底部(不使用任何JS庫),但到目前爲止,我有點困惑在哪使用下列之一。我見過的最有希望的是window.scrollY,但即使滾動到頁面底部,也不會匹配window.innerHeight的值。什麼是最好的方法來做到這一點?確定什麼時候滾動到頁面底部用Javascript

window.innerWidth 
window.innerHeight 

window.outerWidth 
window.outerHeight 

window.scrollX 
window.scrollY 

document.body.scrollWidth 
document.body.scrollHeight 
document.body.scrollTop 
document.body.scrollLeft 

document.body.offsetTop 
document.body.offsetLeft 
document.body.offsetWidth 
document.body.offsetHeight 
+0

爲什麼採取與處理事件手動而不是使用JS庫如jQuery的麻煩? – ThiefMaster 2010-05-12 08:38:31

+7

因爲如果你不懂如何做到這一點,你將無法建立像jquery – Woot4Moo 2010-10-14 19:53:29

回答

24

window.innerHeight + document.body.scrollTop大於或等於document.body.offsetHeight然後你在底部

但由於IE具有這些特性的問題,你需要使用替代屬性,如

document.documentElement.scrollTop滾動和document.documentElement.clientHeight爲窗口的高度

全碼:http://jsbin.com/egegu3/6/edit

+0

這樣的庫完美,謝謝! – chimerical 2010-05-12 16:36:18

+1

基於上述代碼的mootools版本http://jsfiddle.net/KFqpF/7/ – RRG 2011-02-28 16:49:52

6

作爲一個懶惰的人在心臟,我會放一個元素的DIV的最底部,並應用在其上的「element in view」 jQuery插件。 (免責聲明:我與它沒有自己的經驗,但它看起來不錯。)

從博客條目的例子的細微變化:

$('#bottomDIV').bind('inview', function (event, visible) { 
    if (visible == true) { 
    // element is now visible in the viewport 
    highlightButtons(); // or whatever you want to do in the context 
    } 
}); 
0

這工作得很好:

window.onscroll = function() 
{ 
    var scrollHeight, totalHeight; 
    scrollHeight = document.body.scrollHeight; 
    totalHeight = window.scrollY + window.innerHeight; 

    if(totalHeight >= scrollHeight) 
    { 
     console.log("at the bottom"); 
    } 
}