Understanding the window.event property and its usage
I don't un开发者_StackOverflow中文版derstand the motivation behind window.event or window.event.srcElement. In what context should one use this? What exactly does it represent in the DOM?
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';
}
Not sure if this difference has been changed in newer browser versions but basically, "In the Microsoft event accessing model there is a special property window.event that contains the last event that took place." (from reference)
So, to write an event handler compatible across browsers you'd need to do something like this:
function doSomething(e) {
if(!e) {
var e = window.event;
}
var ele = e.target || e.srcElement;
// get the clicked element
// srcElement for IE, target for others
}
element.onclick = doSomething;
Reference: http://www.quirksmode.org/js/events_access.html
function IndentifyMe(){
alert("You clicked on " + window.event.srcElement.tagName);
}
<body onclick = "IndentifyMe()">
Try this code, with lots of element in body tag, and try clicking different element
Events are the lifeblood of user interaction. Without events, you couldn't interact with the page.
Event handlers are used to invoke some JavaScript when a certain action happens. If you want some behavior to be triggered when the user moves their cursor over an element, you use the onmouseover event handler.
"DOM Scripting: Web Design with JavaScript and the Document Object Model: Second Edition"
精彩评论