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

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

问题描述

我有一个div框(称为flux),里面有不同数量的内容。
这个divbox的溢出设置为auto。

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中,但是如果我采用内部高度的通量它返回564px(div设置为500作为高度),'innner'的高度返回1064,而scroll的底部则返回564。

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/

编辑:我已将'bind'更新为'on',具体如下:

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天全站免登陆