如何使用 JQuery .on() 来捕捉滚动事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10625104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use JQuery .on() to catch the scroll event
提问by DFIVE
I'm attempting to use the .on() from jQuery to catch a scroll event that is inside a tag.
我正在尝试使用 jQuery 中的 .on() 来捕获标签内的滚动事件。
so this was my solution:
所以这是我的解决方案:
- the div id='popup'
- the .fixedHeader class is something I'm trying have fixed at the top of the div frame.
getScrollTop() is a javascript function to return the top value (works)
$(document).on("scroll#popup", '#popup', function(){ alert('scrolling'); $(".fixedHeader").css("position", "relative"); $(".fixedHeader").css("top", getScrollTop()); });
- div id='popup'
- .fixedHeader 类是我正在尝试固定在 div 框架顶部的东西。
getScrollTop() 是一个返回最高值的 javascript 函数(有效)
$(document).on("scroll#popup", '#popup', function(){ alert('scrolling'); $(".fixedHeader").css("position", "relative"); $(".fixedHeader").css("top", getScrollTop()); });
采纳答案by Matt Ball
The event is simply scroll
, not scroll#popup
.
该事件是简单的scroll
,不是scroll#popup
。
// http://ejohn.org/blog/learning-from-twitter
// Also, be consistent with " vs '
var $fixedHeader = $('.fixedHeader').css('position', 'relative');
$(document).on('scroll', '#popup', function() {
console.log('scrolling'); // you *really* don't want to alert in a scroll
$fixedHeader.css("top", getScrollTop());
});
回答by Venar303
The confusion is in how "on()" works. In jQuery when you say $(document).on(xx, "#popup", yy) you are trying to run yyy whenever the xx event reaches document but the original target was "#popup".
混淆在于“on()”是如何工作的。在 jQuery 中,当您说 $(document).on(xx, "#popup", yy) 时,只要 xx 事件到达文档,但原始目标是“#popup”,您就会尝试运行 yyy。
If document is not getting the xx event, then that means it isn't bubbling up! The details are in the jQuery On documentation, but the three events "load", "error" and "scroll" do not bubble up the DOM.
如果文档没有得到 xx 事件,那么这意味着它没有冒泡!详细信息在 jQuery On 文档中,但三个事件“load”、“error”和“scroll”不会冒泡 DOM。
This means you need to attach the event directly to the element receiving it. $("#popup").on(xx,yy);
这意味着您需要将事件直接附加到接收它的元素。$("#popup").on(xx,yy);
回答by Tom Halladay
As @Venar303 says, scroll doesn't bubble, thus binding to document will not work.
正如@Venar303 所说,滚动不会冒泡,因此绑定到文档将不起作用。
Use this:
用这个:
$('#popup').on('scroll', function() {});
Instead of this:
取而代之的是:
$(document).on('scroll', '#popup', function() {});