使用 jQuery 检测用户何时滚动到 div 的底部 [英] Detecting when user scrolls to bottom of div with jQuery

查看:40
本文介绍了使用 jQuery 检测用户何时滚动到 div 的底部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 div 框(称为flux),里面有不同数量的内容.此 divbox 已将溢出设置为自动.

I have a div box (called flux) with a variable amount of content inside. This divbox has overflow set to auto.

现在,我想要做的是,当使用滚动到此 DIV 框的底部时,将更多内容加载到页面中,我知道如何执行此操作(加载内容)但我不这样做知道如何检测用户何时滚动到 div 标签的底部?如果我想为整个页面执行此操作,我会使用 .scrollTop 并将其从 .height 中减去.

Now, what I am trying to do, is, when the use scroll to the bottom of this DIV-box, load more content into the page, I know how to do this (load the content) but I don't know how to detect when the user has scrolled to the bottom of the div tag? If I wanted to do it for the entire page, I'd take .scrollTop and subtract that from .height.

但我在这里似乎不能这样做?

But I can't seem to do that here?

我尝试从flux中获取.scrollTop,然后将所有内容包装在一个名为inner的div中,但是如果我获取flux的innerHeight,它会返回564px(div设置为500作为高度)和高度'innner' 它返回 1064,当 div 底部显示 564 时,scrolltop 返回.

I've tried taking .scrollTop from flux, and then wrapping all the content inside a div called inner, but if I take the innerHeight of flux it returns 564px (the div is set to 500 as height) and the height of 'innner' it returns 1064, and the scrolltop, when at the bottom of the div says 564.

我能做什么?

推荐答案

您可以使用一些属性/方法:

There are some properties/methods you can use:

$().scrollTop()//how much has been scrolled
$().innerHeight()// inner height of the element
DOMElement.scrollHeight//height of the content of the element

所以你可以取前两个属性的总和,当它等于最后一个属性时,你就结束了:

So you can take the sum of the first two properties, and when it equals to the last property, you've reached the end:

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

http://jsfiddle.net/doktormolle/w7X9N/

我已将绑定"更新为开启":

I've updated 'bind' to 'on' as per:

从 jQuery 1.7 开始,.on() 方法是将事件处理程序附加到文档的首选方法.

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.

这篇关于使用 jQuery 检测用户何时滚动到 div 的底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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