Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

javascript - Understanding the window.event property and its usage

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here what w3school says about event object:

Events are actions that can be detected by JavaScript, and the event object gives information about the event that has occurred.

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
}

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';
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...