了解 window.event 属性及其用法

Understanding the window.event property and its usage(了解 window.event 属性及其用法)

本文介绍了了解 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';
}

这篇关于了解 window.event 属性及其用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:了解 window.event 属性及其用法

基础教程推荐