如何使用jQuery检查DIV是否滚动到底部

How to check if a DIV is scrolled all the way to the bottom with jQuery

本文关键字:滚动 底部 是否 DIV 何使用 jQuery 检查      更新时间:2023-09-26

我有一个溢出:scroll的div

我想知道它当前是否一直向下滚动。如何使用JQuery?

这个不起作用:我如何确定一个div是否滚动到底部?

这是正确的解决方案(jsfiddle)。简单看一下代码:

$(document).ready(function () {
    $('div').on('scroll', chk_scroll);
});
function chk_scroll(e) {
    var elem = $(e.currentTarget);
    if (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight()) {
        console.log("bottom");
    }
}

function isScrolledToBottom(el) {
    var $el = $(el);
    return el.scrollHeight - $el.scrollTop() - $el.outerHeight() < 1;
}

这是@samccone的答案的变体,包含了@HenrikChristensen关于亚像素测量的评论。

因为它不需要jQuery:

 var isBottom = node.scrollTop + node.offsetHeight === node.scrollHeight;

I do:

 var node = $('#mydiv')[0]; // gets the html element
 if(node) {
    var isBottom = node.scrollTop + node.offsetHeight === node.scrollHeight;
 }

您可以通过

(scrollHeight - scrollTop()) == outerHeight()

代码如下:

$("#div_Id").scroll(function (e) {
    e.preventDefault();
    var elem = $(this);            
    if (elem.scrollTop() > 0 && 
            (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight())) {
        alert("At the bottom");
    }
});

自2012年起,Firefox包含scrollTopMax属性。如果scrollTop === scrollTopMax在元素的底部

不使用jquery,用于onScroll事件

var scrollDiv = event.srcElement.body
window.innerHeight + scrollDiv.scrollTop == scrollDiv.scrollHeight

对我来说,$el.outerHeight()给出了错误的值(由于边界宽度),而$el.innerHeight()给出了正确的值,所以我使用

function isAtBottom($el){
    return ($el[0].scrollHeight - $el.scrollTop()) == $el.innerHeight();
}