用jQuery检测用户滚动到div的底部(Detecting when user scrolls to bottom of div with jQuery)

编程入门 行业动态 更新时间:2024-10-11 11:16:17
用jQuery检测用户滚动到div的底部(Detecting when user scrolls to bottom of div with jQuery)

我有一个div框(称为通量),内容可变的内容。 这个divbox的溢出设置为auto。

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

但我似乎在这里不行吗?

我已经尝试使用.scrollTop从磁通,然后将所有的内容包含在一个称为内部的div中,但如果我采取内在的通量,它返回564像素(div设置为500为高度)和“内在”的高度它返回1064,而滚动的顶端,当在div的底部说564。

我能做什么?

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

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?

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.

What can I do?

最满意答案

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

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

所以你可以得到前两个属性的总和,当它等于最后一个属性时,你已经到了最后:

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

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

编辑:我已将“绑定”更新为“on”:

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

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/

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

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

更多推荐

本文发布于:2023-08-05 16:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1437182.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:用户   div   jQuery   Detecting   bottom

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!