Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

scroll

在document视图或者一个element在滚动的时候,会触发元素的scroll事件。

基本资料

标准
DOM L3, CSSOM View
接口定义
UIEvent
冒泡
elementscroll事件不冒泡, 但是document的defaultView的scroll事件冒泡
能否取消
Target
defaultView, Document, Element
Default Action

属性

Property Type Description
target 只读 EventTarget The event target (the topmost target in the DOM tree).
type 只读 DOMString The type of event.
bubbles 只读 Boolean Whether the event normally bubbles or not
cancelable 只读 Boolean Whether the event is cancellable or not?
view 只读 WindowProxy document.defaultView (window of the document)
detail 只读 long (float) 0.

示例

 scroll 事件可能会被高频度的触发, 因此事件的handler不应执行重型操作,例如DOM操作就不应该放在事件处理中。推荐的处理方案是使用 requestAnimationFrame, setTimeoutcustomEvent,示例代码如下:

使用 window.requestAnimationFrame 优化 Scroll 处理性能

// Reference: https://www.html5rocks.com/en/tutorials/speed/animations/

var last_known_scroll_position = 0;
var ticking = false;

function doSomething(scroll_pos) {
  // do something with the scroll position
}

window.addEventListener('scroll', function(e) {
  last_known_scroll_position = window.scrollY;
  if (!ticking) {
    window.requestAnimationFrame(function() {
      doSomething(last_known_scroll_position);
      ticking = false;
    });
  }
  ticking = true;
});

 

resize 事件的处理同理。

浏览器兼容

iOS UIWebView

在 iOS UIWebViews中, 在视图的滚动过程中,scroll 事件不会被触发;在滚动结束后,scroll 才会触发. 参见 Bootstrap issue #16202. Safari 和 WKWebViews不受此bug影响。

文档标签和贡献者

标签: 
 此页面的贡献者: xuzicn
 最后编辑者: xuzicn,