本文介绍了如何捕获页面上的所有滚动事件,而不会将每个单个容器附加onscroll处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下网页:

 <html>
   <body onscroll="alert('body scroll event')">
     <div style='width:200px;height:200px;overflow:auto' onscroll="alert('div scroll event')">
       <div style='height:400px'>
       </div>
     </div>
   </body>
 </html>

这个html用滚动条创建一个div。如果移动滚动条,则会触发div元素上的onscroll事件。但是,身体上的滚动事件不会被触发。这是预期的,因为W3C声明元素onroll的事件不会泡沫。

This html creates a div with a scrollbar. If you move the scrollbar, the "onscroll" event on the div element is triggered. However, the "onscroll" event on the body is NOT fired. This is expected, since the W3C states that element onscroll events do not "bubble".

但是,我正在开发一个客户端Web框架,需要知道任何时间滚动页面的任何元素上的滚动条。如果onscroll冒泡,这很容易,但不幸的是没有。是否有任何其他方式来检测整个页面上的滚动事件? (现在我主要关注Webkit,所以Webkit特定的解决方案会很好...)

However, I'm developing a client-side web framework that needs to know any time a scroll bar on ANY element of the page is scrolled. This would be easy to do if "onscroll" bubbled, but unfortunately it does not. Is there any other way to detect onscroll events across an entire page? (Right now I'm focusing mainly on Webkit, so a Webkit-specific solution would be fine...)

这里有一些我试过的东西:
1.捕获DOMAttrModified(似乎不会触发移动滚动条)
2.使用DOM观察器(也似乎不触发滚动条)
3.更改onscroll事件键入泡沫(似乎不可能)

Here are some things I've tried: 1. Capturing DOMAttrModified (doesn't seem to fire for moving scrollbars.) 2. Using DOM Observers (also don't seem to fire for scrollbars) 3. Changing the "onscroll" event type to bubble (seems to not be possible)

看起来,捕获全局onscroll事件的唯一方法是将onscroll事件附加到可能滚动的每个元素,即非常丑,会伤害我的框架的表现。

It seems the ONLY way to capture onscroll events globally is to attach an onscroll event to EVERY element that may scroll, which is very ugly and is going to hurt the performance of my framework.

任何人都知道一个更好的方法?

Anyone know a better way?

谢谢提前!

推荐答案

在现代浏览器中检测所有滚动事件的最简单的方法是使用捕获而不是冒泡当附加事件时:

The simplest way to detect all scroll events in modern browser would be using 'capturing' rather than 'bubbling' when attaching the event:

window.addEventListener('scroll', function(){ code goes here }, true)

遗憾的是,我知道在旧版浏览器中没有任何等价物,例如< = IE8

Unfortunately as I am aware there is no equivalent in older browser such as <= IE8

这篇关于如何捕获页面上的所有滚动事件,而不会将每个单个容器附加onscroll处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-10 22:38