目录

window addEventListener()

示例

向窗口添加单击事件处理程序:

window.addEventListener("click", myFunction);

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

更简单的语法:

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

下面有更多示例。


描述

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


语法

window.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


更多示例

您可以向窗口添加许多事件侦听器:

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

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

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

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

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

更改文档的背景颜色:

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

使用removeEventListener()方法:

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

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

浏览器支持

addEventListener所有浏览器都支持:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes