問題描述
我不明白 window.event 或 window.event.srcElement 背后的動機.在什么情況下應該使用它?它在 DOM 中究竟代表什么?
I don't understand the motivation behind window.event or window.event.srcElement. In what context should one use this? What exactly does it represent in the DOM?
推薦答案
這里 w3school 說什么 關于事件
對象:
事件是可以被 JavaScript 檢測到的動作,而事件對象提供有關已發生事件的信息.
Events are actions that can be detected by JavaScript, and the event object gives information about the event that has occurred.
有時我們想在事件發生時執行 JavaScript,例如就像用戶點擊按鈕一樣.
Sometimes we want to execute a JavaScript when an event occurs, such as when a user clicks a button.
您可以使用以下方式處理事件:
You can handle events using:
node.onclick = function(e) {
// here you can handle event. e is an object.
// It has some usefull properties like target. e.target refers to node
}
但是 Internet Explorer 不會將事件傳遞給處理程序.相反,您可以使用 window.event 對象,該對象在事件觸發后立即更新.那么跨瀏覽器處理事件的方式:
However Internet Explorer doesn't pass event to handler. Instead you can use window.event object which is being updated immediately after the event was fired. So the crossbrowser way to handle events:
node.onclick = function(e) {
e = e || window.event;
// also there is no e.target property in IE.
// instead IE uses window.event.srcElement
var target = e.target || e.srcElement;
// Now target refers to node. And you can, for example, modify node:
target.style.backgroundColor = '#f00';
}
這篇關于了解 window.event 屬性及其用法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!