简体   繁体   English

如何检测用户何时滚动到 jQuery 中的 div 底部?

[英]How to detect when a user has scrolled to the bottom of a div in jQuery?

There are a few people who have already asked this question but the last one I can see is almost 10 years old and the code that was given in the answer doesn't seem to work or at the very least doesn't work every time so I thought I would write this as it seems like the code is outdated.有几个人已经问过这个问题,但我能看到的最后一个已经有将近 10 年的历史了,答案中给出的代码似乎不起作用,或者至少每次都不起作用所以我想我会写这个,因为看起来代码已经过时了。

Anyway, I have a div with the id terms, the overflow is set to auto so it is scrollable.无论如何,我有一个带有 id 术语的 div,溢出设置为自动,因此它是可滚动的。 I want a hidden div to become visible when the user has scrolled to the bottom of the terms div.当用户滚动到术语 div 的底部时,我希望隐藏的 div 变得可见。 At the moment I'm using this目前我正在使用这个

jQuery(function($) {
    $('#terms').on('scroll', function() {
        if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
            alert('end reached');
        }
    })
});

but it doesn't work.但它不起作用。

Your code works well for me.你的代码很适合我。 You can test this code too.您也可以测试此代码。 I hope this help you:我希望这可以帮助你:

jQuery(function ($) {
        $('#terms').bind('scroll', function () {
          if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
                    alert('end reached');
                }
            })
        });

Thanks to Elham linking me to this page https://www.w3docs.com/tools/code-editor/10827 the page had a negative value on it's if statement I added -100 to my if statement and that gave the event a bit of padding and it works every time.感谢 Elham 将我链接到此页面https://www.w3docs.com/tools/code-editor/10827该页面的 if 语句为负值,我在 if 语句中添加了 -100,这使事件有点填充,它每次都有效。

jQuery(function ($) {
    $('#terms').bind('scroll', function () {
      if ($(this).scrollTop() + $(this).height() >= $(this)[0].scrollHeight - 100) {
                alert('end')
            }
        })
    });

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

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