如何通过JavaScript检测指定元素的滚动结束? [英] How can I detect scroll end of the specified element by JavaScript?

查看:72
本文介绍了如何通过JavaScript检测指定元素的滚动结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Google Chrome 10 and writing JavaScript to detect scroll end.

要检测窗口的滚动结尾,下面的代码工作正常:

To detect scroll end of window, the code below worked fine:

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 =boxstyle =height:500px; overflow:auto;>

这是无法正确检测的代码:

Now I want to detect scroll end of the specified element, like <section id="box" style="height: 500px; overflow: auto;">
This is the code that doesn't detect correctly:

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
);

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

Could someone please fix my code? Thanks.

推荐答案

已修复。

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
)

这篇关于如何通过JavaScript检测指定元素的滚动结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆