了解 window.event 属性及其用法
我不明白 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';
}
相关文章