If event processing is involved when javascript is used, you need to know the differences between events in different browsers. There are three types of javascript event models: NN4, IE4 +, and W3C/Safari. This also leads to differences in event processing in different browsers, the following code is used to describe how to make the event work normally in IE4 + and Firefox.
First, check the following code:
The Code is as follows:
Function doEventThing (eventTag ){
Var event = eventTag | window. event;
Var currentKey = event. charCode | event. keyCode;
Var eventSource = window. event. srcElement | eventTag.tar get;
}
This code is mainly used to handle keyboard events. In IE, event can be directly used as an attribute of the window object, but W3C model is used in Firefox, it transmits events by passing parameters. That is to say, You need to provide an interface for Event Response for your function. In the above functions,
EventTag plays this role.
Var event = eventTag | window. event;
This code can get the correct event according to the browser and use it in the program. If this code is used under IE4 +, because eventTag is null, event = window can be guaranteed. event, but if it is run in Firefox, var event = eventTag is given manually. Based on the analysis of this piece of code, we can easily see that the doEventThing method can be transformed as follows (because javascript allows us to explicitly specify the number of parameters when defining a function ):
The Code is as follows:
Function doEventThing (){
Var event = arguments [0] | window. event;
// Other code
}
In Firefox, arguments [0] is used as a parameter to spread events (when no function parameter is explicitly specified) in a specific scenario ............
Var currentKey = event. charCode | event. keyCode; is also caused by different browsers. keyCode is recorded under IE4 +, but charCode is recorded under Firefox. Therefore, we need to deal with their differences.
Another difference is the acquisition of event sources: Through statements
Var eventSource = window. event. srcElement | eventTag.tar get;
We also see the difference between IE and W3C.
After the above packaging, we can basically use the event mechanism smoothly under IE4 + and Firefox, of course, if we can encapsulate this difference to form our own Event object and use the Event object in the program, we will not introduce it here.
Next, we will analyze the binding of events: There are five types:
1. bind to an element, which is also a common example:
In this way, we bind doEventThing to the button object and click this button to trigger the event.
2. Bind events to objects: this is also a common one, especially under IE4 +:
Document. getElementById ("pid"). onclick = doEventThing;
3. Use