Cửa sổ addEventListener()
Ví dụ
Thêm trình xử lý sự kiện nhấp chuột vào cửa sổ:
window.addEventListener("click", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
Hãy tự mình thử »Cú pháp đơn giản hơn:
window.addEventListener("click", function(){
document.getElementById("demo").innerHTML = "Hello World";
});
Hãy tự mình thử »Thêm ví dụ dưới đây.
Sự miêu tả
Phương thức addEventListener()
gắn một trình xử lý sự kiện vào một cửa sổ.
Phương pháp tài liệu
Phương thức addEventListener()
Phương thức RemoveEventListener()
Phương thức phần tử
Phương thức addEventListener()
Phương thức RemoveEventListener()
Hướng dẫn
Cú pháp
window.addEventListener( event , function , Capture )
Thông số
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.
|
Giá trị trả về
NONE |
Thêm ví dụ
Bạn có thể thêm nhiều trình xử lý sự kiện vào một cửa sổ:
window.addEventListener("click", myFunction1);
window.addEventListener("click", myFunction2);
Hãy tự mình thử »Bạn có thể thêm các loại sự kiện khác nhau:
window.addEventListener("mouseover", myFunction);
document.addEventListener("click", someOtherFunction);
window.addEventListener("mouseout", someOtherFunction);
Hãy tự mình thử »Khi truyền tham số, hãy sử dụng "hàm ẩn danh" để gọi hàm có tham số:
window.addEventListener("click", function() {
myFunction(p1, p2);
});
Hãy tự mình thử »Thay đổi màu nền của tài liệu:
window.addEventListener("click", function(){
document.body.style.backgroundColor = "red";
});
Hãy tự mình thử »Sử dụng phương thức RemoveEventListener():
// Add an event listener
window.addEventListener("mousemove", myFunction);
// Remove the event listener
window.removeEventListener("mousemove", myFunction);
Hãy tự mình thử »Hỗ trợ trình duyệt
addEventListener
được hỗ trợ trong tất cả các trình duyệt:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |