JavaScript事件處理程序的最新功能是事件監(jiān)聽。事件監(jiān)聽監(jiān)視元素上的事件。
我們將使用addEventListener()方法來代替將事件直接分配給元素上的屬性。
addEventListener()方法將事件處理程序附加到指定的元素。
我們可以重寫隨機(jī)顏色示例(來自上一章),如下所示:
document.querySelector("button").addEventListener("click", bgChange); function bgChange() { let color = "rgb(" + random(255) + "," + random(255) + "," + random(255) + ")"; document.body.style.backgroundColor = color; }測試看看?/?
我們?nèi)匀皇褂门c以前相同的bgChange()函數(shù)。我們將addEventListener()方法附加到按鈕上。
addEventListener() 接受兩個(gè)必填參數(shù)-要監(jiān)聽的事件和監(jiān)聽器回調(diào)函數(shù)。
此方法與事件處理程序?qū)傩裕ㄉ弦徽拢┫嗨?,但是語法明顯不同。
element.addEventListener(event, listener, useCapture)
第一個(gè)參數(shù)是事件的類型(例如“ click”或“ mousemove”)。
第二個(gè)參數(shù)是事件發(fā)生時(shí)我們要調(diào)用的監(jiān)聽函數(shù)。
第三個(gè)參數(shù)是一個(gè)布爾值,指定是使用事件冒泡還是使用事件捕獲。此參數(shù)是可選的。
注意,不要為事件使用“ on”前綴。使用“ click”代替“ onclick”。
請注意,將所有代碼放入addEventListener()方法中的匿名函數(shù)中是非常合適的,如下所示:
let para = document.querySelector("#para"); para.addEventListener("click", function() { this.innerHTML = "Hello world"; });測試看看?/?
您還可以引用外部“命名”函數(shù):
let para = document.querySelector("#para"); para.addEventListener("click", changeText); function changeText() { para.innerHTML = "Hello world"; }測試看看?/?
乍一看,事件監(jiān)聽似乎與事件處理程序?qū)傩苑浅O嗨?,但是它們有一些?yōu)點(diǎn)。我們可以在同一元素上設(shè)置多個(gè)事件監(jiān)聽,如以下示例所示:
document.querySelector("button").addEventListener("click", myFunc); document.querySelector("button").addEventListener("click", anotherFunc);測試看看?/?
我們可以向元素添加不同類型的事件:
document.querySelector("button").addEventListener("mouseenter", myFunc1); document.querySelector("button").addEventListener("click", myFunc2); document.querySelector("button").addEventListener("mouseout", myFunc3);測試看看?/?
傳遞參數(shù)值時(shí),請使用匿名函數(shù),該函數(shù)使用參數(shù)調(diào)用指定的函數(shù):
var btn = document.querySelector("button"); btn.addEventListener("click", function() { myFunc(x, y); });測試看看?/?
此外,您可以addEventListener()在文檔和窗口對象上使用。
本示例使用以下addEventListener()方法將click事件附加到文檔:
document.addEventListener("click", function() { alert("Hello World!!!"); });測試看看?/?
本示例使用該addEventListener()方法將調(diào)整大小(resize)事件附加到窗口:
window.addEventListener("resize", function() { box.innerHTML = Math.random(); });測試看看?/?
當(dāng)前,事件監(jiān)聽是處理JavaScript中事件的最常見和首選方式。
也可以使用該removeEventListener()方法從元素中刪除一個(gè)或所有事件。
var box = document.getElementById("para"); // Attach an event handler to a P element with id="para" box.addEventListener("mousemove", myFunc); // Remove the event handler from a P element with id="para" box.removeEventListener("mousemove", myFunc);測試看看?/?
第一個(gè)參數(shù)是事件的類型(例如“ click”或“ mousemove”)。
第二個(gè)參數(shù)是事件發(fā)生時(shí)我們要調(diào)用的函數(shù)。
JavaScript參考:HTML DOM事件對象參考