这两者有什么区别吗?
$(window).on('scroll', function() { /**/ });
和
$(document).on('scroll', function() { /**/ });
我问的原因是我注意到如果我有 2 个处理程序(一个在 window
上监听,第二个在 document
) 并且在某些时候我将 return false;
在 document
中,window
处理程序停止触发,即使事件是命名空间的.
您可以看到行为 here 。从顶部滚动超过 300 像素后,window
处理程序的计数不再增加。
如果我将 window
选择器更改为 document
,则不会发生冲突。
和 fiddle 代码:
HTML
<div class="fixed">
<div>document scroll event: <span class="scroll1">0</span></div>
<div>window scroll event: <span class="scroll2">0</span></div>
</div>
CSS
body {
height: 3000px;
}
.fixed {
position: fixed;
top: 20px;
left: 20px;
}
JS
$(function () {
var $scroll1 = $('.scroll1');
var $scroll2 = $('.scroll2');
function updateCount($el) {
$el.text(parseInt($el.text(), 10) + 1);
}
$(document).on('scroll', function () {
updateCount($scroll1);
if ($(this).scrollTop() > 300) {
return false;
}
});
$(window).on('scroll', function () {
updateCount($scroll2);
});
});
最佳答案
事件泡泡
你拥有的是
window
|
v
document
|
v
body
事件是这样处理的
- user scrolls on body
- Event scroll is triggered on
body
check event handlers
3.1. if any event handler onbody
returns false stop here
3.2. if no event handlers registered or all event handlers return true, null or undefined pass scroll event to parent(document, goto step 4)Event scroll is triggered on
document
check event handlers
5.1. if any event handler ondocument
returns false stop here
5.2. if no event handlers registered or all event handlers return true, null or undefined pass scroll event to parent(window goto step 6)Event scroll is triggered on
window
- check event handlers
7.1. if any event handler onwindow
returns false stop here
7.2. if no event handlers registered or all event handlers return true, null or undefined call other event handlers that come after this one.
你可以看到断点在#.1
如果其中任何一个返回 false,则整个气泡序列将停止。这就像火车上的紧急刹车。不仅您的手推车会停在您的范围/定位位置,而且整个火车都会停。
关于javascript - 在窗口和文档上监听滚动事件会导致处理程序之间发生冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48443225/