2014-09-19 77 views
0

我正在嘗試對頁面進行無限滾動,但測試頁面底部的條件是否在Chrome上無法正常運行。在Chrome上,此警報似乎觸發在頁面的頂部,而不是觸及底部。它在IE11上正常工作。要在頁面上檢測頁面底部的JavaScript是否相反

在Chrome $(document).height()等於0.我的頁面頂部有一個<!DOCTYPE html> html,如果它很重要的話。

奇怪的是我把這個從另一個例子它的工作完美的jsfiddle內的瀏覽器:http://jsfiddle.net/nick_craver/gWD66/

$(window).scroll(function() { 
     if ($(window).scrollTop() + $(window).height() == $(document).height()) { 
      alert("test"); 
     } 
    } 
} 
+2

你可以發佈你的整個頁面嗎? – Max 2014-09-19 20:57:05

+0

不幸的是我必須保持私密。 – 2014-09-19 20:59:25

+1

對我來說(在Chrome中)它完美的工作,這代碼究竟是什麼問題? – algorhythm 2014-09-19 21:04:26

回答

0

以下功能似乎提供了最終的失敗證明的解決方案獲得頁面的正確的高度,至少在我的情況。

function getDocHeight() { 
    var doc = document; 
    return Math.max(
     Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight), 
     Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight), 
     Math.max(doc.body.clientHeight, doc.documentElement.clientHeight) 
    ); 
} 
1

什麼樣的CSS應用到網頁,更使體內元素?這可能是使$(document).height()等於比$(window).scrollTop()和$(window).height()的組合更多的一些填充或邊距。以下代碼將幫助您確定您是否真的符合if()條件。

你使用的是什麼版本的jQuery?

$(window).scroll(function() { 
 
    var scrollPosition = $(window).scrollTop() + $(window).height(); 
 
    var bodyHeight = $(document).height(); 
 
    $("#scrollIndex").html(scrollPosition + "/" + bodyHeight); 
 
    if(scrollPosition == bodyHeight) { 
 
     $("#scrollIndex").html("BOTTOM!"); 
 
     $('body').height(bodyHeight + 200 + "px"); 
 
    } 
 
});
body{ 
 
\t height:2000px; 
 
} 
 
#scrollIndex{ 
 
\t position:fixed; 
 
    \t top:0px; 
 
    \t right:0px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div id='scrollIndex'></div>

+0

這很有幫助,謝謝! – 2014-09-22 18:40:41