繁体   English   中英

如何通过JavaScript检测指定元素的滚动结束?

[英]How can I detect scroll end of the specified element by JavaScript?

我正在使用谷歌Chrome 10并编写JavaScript来检测滚动结束。

要检测window滚动结束,下面的代码工作正常:

window.addEventListener(
    'scroll',
    function()
    {
        var scrollTop = document.documentElement.scrollTop ||
            document.body.scrollTop;
        var offerHeight = document.body.offsetHeight;
        var clientHeight = document.documentElement.clientHeight;
        if (offsetHeight <= scrollTop + clientHeight)
        {
            // Scroll end detected
        }
    },
    false
);

现在我想检测指定元素的滚动结束,例如<section id="box" style="height: 500px; overflow: auto;">
这是无法正确检测的代码:

document.getElementById('box').addEventListener(
    'scroll',
    function()
    {
        var scrollTop = document.getElementById('box').scrollTop;
        var offerHeight = document.getElementById('box').offsetHeight;
        var clientHeight = document.getElementById('box').clientHeight;
        if (offsetHeight <= scrollTop + clientHeight)
        {
            // This is called before scroll end!
        }
    },
    false
);

有人可以修改我的代码吗? 谢谢。

固定。

document.getElementById('box').addEventListener(
    'scroll',
    function()
    {
        var scrollTop = document.getElementById('box').scrollTop;
        var scrollHeight = document.getElementById('box').scrollHeight; // added
        var offsetHeight = document.getElementById('box').offsetHeight;
        // var clientHeight = document.getElementById('box').clientHeight;
        var contentHeight = scrollHeight - offsetHeight; // added
        if (contentHeight <= scrollTop) // modified
        {
            // Now this is called when scroll end!
        }
    },
    false
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM