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

时间:2011-04-03 03:06:37

标签: javascript google-chrome scroll

我正在使用Google 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
);

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

1 个答案:

答案 0 :(得分:7)

固定。

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
)