目录

HTML DOM 文档 addEventListener()

示例

在文档中添加点击事件:

document.addEventListener("click", myFunction);

function myFunction() {
  document.getElementById("demo").innerHTML = "Hello World";
}
亲自试一试 »

更简单的语法:

document.addEventListener("click", function(){
  document.getElementById("demo").innerHTML = "Hello World";
});
亲自试一试 »

下面有更多示例。


描述

这个addEventListener()方法将事件处理程序附加到文档。


语法

document.addEventListener( event, function, Capture)

参数

Parameter Description
event Required.
The event name.
Do not use the "on" prefix.
Use "click" instead of "onclick".

All HTML DOM events are listed in the:
HTML DOM Event Object Reference.
function Required.
The function to run when the event occurs.

When the event occurs, an event object is passed to the function as the first parameter. The type of the event object depends on the specified event. For example, the "click" event belongs to the MouseEvent object.
capture Optional (default = false).
true - The handler is executed in the capturing phase.
false - The handler is executed in the bubbling phase.

返回值

NONE


更多示例

您可以向文档添加许多事件侦听器:

document.addEventListener("click", myFunction1);
document.addEventListener("click", myFunction2);
亲自试一试 »

您可以添加不同类型的事件:

document.addEventListener("mouseover", myFunction);
document.addEventListener("click", someOtherFunction);
document.addEventListener("mouseout", someOtherFunction);
亲自试一试 »

传递参数时,使用 "anonymous function" 来调用带参数的函数:

document.addEventListener("click", function() {
  myFunction(p1, p2);
});
亲自试一试 »

更改文档的背景颜色:

document.addEventListener("click", function(){
  document.body.style.backgroundColor = "red";
});
亲自试一试 »

使用removeEventListener()方法:

// Add an event listener
document.addEventListener("mousemove", myFunction);

// Remove event listener
document.removeEventListener("mousemove", myFunction);
亲自试一试 »

浏览器支持

document.addEventListener是 DOM Level 2 (2001) 功能。

所有浏览器都完全支持它:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11