了解window.event属性及其用法 [英] Understanding the window.event property and its usage

查看:412
本文介绍了了解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.

你可以处理事件:

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属性及其用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆