MDN wants to learn about developers like you: https://qsurvey.mozilla.com/s3/MDN-dev-survey

正在翻譯中。

當文件的可視區或元素被滾動(scroll),scroll事件會被觸發

一般資訊

規範
DOM L3, CSSOM View
介面
UIEvent
Bubbles
Not on elements, but bubbles to the default view when fired on the document
Cancelable
No
Target
defaultView, Document, Element
Default Action
None

屬性

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

Example

因為 scroll 事件是高頻觸發,這樣的事件處理程式不該進行運算成本高的程式,像是DOM的修改。所以,建議使用 requestAnimationFrame, setTimeoutcustomEvent 如下所示

Scroll optimization with window.requestAnimationFrame

// Reference: http://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 事件不會觸發;它們要等到滾動完成時才被觸發。請參閱Bootstrap issue #16202。 Safari 和 WKWebViews 不受此bug的影響。

文件標籤與貢獻者

 此頁面的貢獻者: dwatow
 最近更新: dwatow,