Document:scroll事件

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2020.

scroll 事件會在捲動文件的可視區域時觸發。元件(Element)捲動相關請參見Element: scroll事件

Bubbles
Cancelable
介面 Event
事件處理常式的屬性 onscroll

备注: iOS 的 UIWebViews 中,scroll事件不會在捲動時觸發,而只在捲動結束後觸發。請參見 Bootstrap issue #16202。Safari 和 WKWebViews 不受本 bug 影響。

範例

限制捲動事件的觸發次數

Since scroll events can fire at a high rate, the event handler shouldn't execute computationally expensive operations such as DOM modifications. Instead, it is recommended to throttle the event using requestAnimationFrame(), setTimeout(), or a CustomEvent, as follows.

Note, however, that input events and animation frames are fired at about the same rate, and therefore the optimization below is often unnecessary. This example optimizes thescroll event for requestAnimationFrame.

有鑒於 scroll 事件可能會以很高的速率觸發,事件處理常式不應執行計算密集的操作(如 DOM 修改)。所以,建議改用 requestAnimationFrame()setTimeout()CustomEvent 以調控事件的觸發次數,如下。

不過需要注意,輸入事件和動畫影格的觸發速率大致相同,因此通常沒有必要進行下述的最佳化。本範例最佳化requestAnimationFramescroll事件。

js
// 參考來源:http://www.html5rocks.com/en/tutorials/speed/animations/

let lastKnownScrollPosition = 0;
let ticking = false;

function doSomething(scrollPos) {
  // 依據捲動位置進行某些操作
}

document.addEventListener("scroll", function (e) {
  lastKnownScrollPosition = window.scrollY;

  if (!ticking) {
    window.requestAnimationFrame(function () {
      doSomething(lastKnownScrollPosition);
      ticking = false;
    });

    ticking = true;
  }
});

更多類似範例可見resize事件頁面。

規格

Specification
CSSOM View Module
# eventdef-document-scroll
HTML Standard
# handler-onscroll

瀏覽器相容性

BCD tables only load in the browser

延伸閱讀