[英]jQuery height doesn't equal scrollTop
在我的jquery中,我试图计算滚动条距底部的距离为100px,当滚动条到达底部时,我将执行ajax查询(目前,您正在查看警报)。
$(document).on("scroll", function(e){
var scrollHeight = $(document).height();
var offset = $(document).scrollTop();
console.log(scrollHeight);
console.log(offset);
if(scrollHeight - offset <= 100){
alert("here");
}
});
由于某种原因,我无法弄清楚它是行不通的。 如果我滚动到底部,我将假定height()
等于scrollTop()
但事实并非如此,这是显示的内容:
scrollHeight = 1923
offset = 998
我为此使用了错误的方法吗?
您需要使用scrollTop
添加window
的高度。 链接
$(document).on('scroll', function () {
var docHeight = $(document).height(),
scrollTop = $(document).scrollTop(),
windowHeight = $(window).height();
if (docHeight - (scrollTop + windowHeight) <= 100) {
alert(docHeight - (scrollTop + windowHeight));
}
});
看起来您可能忘记了减去窗格的可见高度。 我在这里的代码中做了类似的操作:
var scrollPos = $('#viewable-div').height() - $('#scrolling-content').height();
if ($("#scrolling-content").scrollTop() > (scrollPos - 100)) {
//load more
}
当您完全向下滚动元素时,scrollHeight应该等于scrollTop + clientHeight。
如果该元素没有滚动条,则scrollWidth / Height应等于clientWidth / Height。
•当元素没有滚动条时,IE使scrollHeight等于内容的实际高度; 而不是元素的高度。 scrollWidth是正确的,但在IE8中除外,它的距离是5像素。
•Opera给出奇数,错误值。
您可以使用这样的语句
((container.scrollTop() + container.height() + detectionOffset) >=
container.get(0).scrollHeight)
其中container可以是document.body和detectionOffset为100
这已经被回答过几次了,包括这里
我正在使用并且始终在运行的代码(甚至在Opera上)是这样的:
$(window).on("scroll", function () {
var scrollHeight = $(document).height();
var scrollPosition = $(window).height() + $(window).scrollTop();
if ((scrollHeight - scrollPosition) / scrollHeight === 0) {
/* Do something */
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.