EventListener

Baseline Widely available *

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

* Some parts of this feature may have varying levels of support.

EventListener 介面表示一個可以處理由 EventTarget 物件分派事件的物件。

備註: 基於相容舊版內容的需要, EventListener 可以接受一個函式及一個帶有 handleEvent() 屬性函式的物件。相關的範例顯示在下方。

屬性

這個介面並不實作且不繼承任何屬性。

方法

這個介面不繼承任何方法。

EventListener.handleEvent()

一個可以在指定類型事件發生時被呼叫的函數。

範例

HTML

html
<button id="btn">Click here!</button>

JavaScript

js
const buttonElement = document.getElementById("btn");

// 透過提供回呼函數的方式對「click」事件新增處理器。
// 當元素被點選後會出現「Element clicked!」的彈出訊息。
buttonElement.addEventListener("click", function (event) {
  alert("Element clicked through function!");
});

// 基於相容性,一個帶有 `handleEvent` 的非函式物件可被視為處理函式。
buttonElement.addEventListener("click", {
  handleEvent: function (event) {
    alert("Element clicked through handleEvent property!");
  },
});

結果

檢閱相關

規格

Specification
DOM
# ref-for-dom-eventtarget-addeventlistener③

瀏覽器相容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
addEventListener
Form with options object supported (third parameter can be either options or a Boolean, for backwards compatibility)
options.capture parameter
options.once parameter
options.passive parameter
options.passive parameter defaults to true for touchstart and touchmove events
options.passive parameter defaults to true for wheel and mousewheel events
options.signal parameter
useCapture parameter is optional

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support
See implementation notes.