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

问题描述

考虑以下网页:

 

这个 html 创建了一个带有滚动条的 div.如果移动滚动条,则会触发 div 元素上的 onscroll 事件.但是,不会触发正文上的 onscroll 事件.这是意料之中的,因为 W3C 声明元素 onscroll 事件不会冒泡".

但是,我正在开发一个客户端 Web 框架,它需要知道页面任何元素上的滚动条何时滚动.如果 onscroll 冒泡,这很容易做到,但不幸的是它没有.有没有其他方法可以检测整个页面的 onscroll 事件?(现在我主要关注 Webkit,因此特定于 Webkit 的解决方案就可以了...)

以下是我尝试过的一些方法:

  1. 捕获 DOMAttrModified(似乎不会触发移动滚动条.)
  2. 使用 DOM Observers(似乎也不会触发滚动条)
  3. onscroll 事件类型更改为冒泡(似乎不可能)

似乎全局捕获 onscroll 事件的唯一方法是将 onscroll 事件附加到每个可能滚动的元素上,这非常难看并且会伤害我的框架的性能.

有人知道更好的方法吗?

解决方案

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

window.addEventListener('scroll', function(){ 代码在这里}, true)

不幸的是,据我所知,在诸如 <= IE8

之类的旧浏览器中没有等效项

Consider the following Web page:

 <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>

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".

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...)

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)

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)

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

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

06-11 05:59