EventListener

EventListener 接口表示的对象可以处理 EventTarget 对象所调度的事件。

Note: 由于需要与以前遗留的内容进行兼容,EventListener 可以接受一个函数,也可以接受带有 handleEvent() 函数属性的对象。这将在下面的例子中展现出来。

属性

此接口未实现或继承任何属性。

方法

此接口未继承任何方法。

EventListener.handleEvent()
一个在特定类型的事件被调用时运行的函数。

例子

HTML

<button id="btn">点这里!</button>

JavaScript

const buttonElement = document.getElementById('btn');

// Add a handler for the 'click' event by providing a callback function.
// Whenever the element is clicked, a pop-up with "Element clicked!" will
// appear.
buttonElement.addEventListener('click', function (event) {
  alert('Element clicked through function!');
});

// 由于兼容性原因,一个带有 handleEvent 函数属性的对象也可以达到相同的效果。
buttonElement.addEventListener('click', {
  handleEvent: function (event) {
    alert('Element clicked through handleEvent property!');
  }
});

结果

参见:

规范

规范 状态 备注
DOM
EventListener
Living Standard No change.
Document Object Model (DOM) Level 2 Events Specification
EventListener
Obsolete Initial definition.

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
EventListenerChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 9Opera Full support 7Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android ?
handleEventChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 9Opera Full support 7Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android ?

Legend

Full support  
Full support
Compatibility unknown  
Compatibility unknown