Event models differ _javascript techniques in different browsers

Source: Internet
Author: User
Tags button type eval event listener

Standard reference

The Eventtarget interface is implemented by all nodes (node) that support the DOM event model, according to the 2 events description of the DOM. The interface provides a ' AddEventListener ' and ' RemoveEventListener ' method for binding or unbinding a eventlisteners interface to a eventtarget.

The event interface is defined in the DOM 2 events to provide contextual information about the event, which provides several standard properties and methods. Objects that implement the event interface are typically passed in as the first argument to the event-handler function to provide some information about the current event.

The DOM 2 event model allows the DOM to implement multiple modules that support events, and if necessary, the event model allows the addition of new event modules. For common purposes, the DOM defines a UI event module that contains low-level, device-dependent event modules, a UI logic event module, and a document Change event module. Third-party implementations (such as browser vendors) when defining a new type event, the event name must not start with a case-insensitive ' dom ' string, which is reserved for future DOM event modules.

DOM 2 has defined a UI event type module and a mouse event type module that corresponds to the uievent and MouseEvent interfaces respectively. These two interfaces provide several standard properties and methods to learn some information when an event occurs.

For more information about the Eventtarget interface, refer to DOM 2 Events 1.3. Event Listener Registration.

For more information about the Event interface, refer to DOM 2 Events 1.4. Event interface.

For more information about event modules, refer to DOM 2 events 1.6. Event module definitions.

Problem description

Each browser has a difference in how elements are bound, how to bind event listeners, how to get event objects, and how to implement events objects.

The impact

If you use a browser-specific event-related properties and methods to write code, it can cause compatibility problems, resulting in code error, failure of functionality.

Affected browsers

All browsers

Problem analysis

1. Only IE Opera supports the use of ' attachevent ' and ' detachevent ' methods to bind and Unbind event listeners

As described in DOM 2 events, nodes use the ' AddEventListener ' and ' RemoveEventListener ' methods to bind and Unbind event listeners, but IE6 IE7 IE8 does not support both methods and uses ' Attachevent ' And the ' detachevent ' method as an alternative, Opera two methods are supported. Chrome Safari Firefox only supports standard methods.

Analyze the following code:

<button id= "Add" type= "button" >add Event listener test</button> <button id= "Remove" type= "button" > Remove Event listener test</button> <div id= "info" ></div> <script type= "Text/javascript" > var Add = document.getElementById ("Add"), remove = document.getElementById ("Remove"), SHOWMSGA = function () {showmsg ("Attac

	Hevent ")}, SHOWMSGB = function () {showmsg (" AddEventListener ")};
		if (add.attachevent) {add.attachevent ("onclick", SHOWMSGA);
	Remove.attachevent ("onclick", removee);
		} if (Add.addeventlistener) {Add.addeventlistener ("click", Showmsgb,false);
	Remove.addeventlistener ("click", Removee,false);
			function Removee () {if (add.detachevent) {add.detachevent ("onclick", SHOWMSGA);
		ShowMsg ("DetachEvent");
			} if (Add.removeeventlistener) {Add.removeeventlistener ("click", Showmsgb,false);
		ShowMsg ("RemoveEventListener"); The function ShowMsg (method) {document.getElementById ("info"). InnerHTML + = ("Support" + Method + "&Lt;br/> ");
 } </script>

Click on ' Add Event Listener test ' >> ' Remove event listener test ' >> ' Add Event Listener test ', testing each browser's support for these methods, resulting in Under

IE6 IE7 IE8
Opera
Chrome Safari Firefox

There are a few things to note about ' AddEventListener ' and ' attachevent ':

    • IE does not support triggering event listeners during the capture phase, and the ' attachevent ' method does not provide parameters to indicate whether to respond to events triggered during the capture phase;
    • ' AddEventListener ' and ' attachevent ' can register multiple event listeners;
    • Registering the same event listener multiple times in Firefox Chrome Safari, the duplicate registrations are discarded, and the event listeners that are repeatedly registered in IE are repeatedly executed repeatedly;
    • When multiple event listeners are registered for the same element, the sequence of IE6 IE7 event listeners is random, IE8 is in reverse order, and Firefox Chrome Safari Opera is sequential;
    • When an element registers an event listener with an illegal event listener (not a function), an exception is thrown in IE Firefox, and an illegal event listener is ignored in the Chrome Safari Opera, and other event listeners continue to execute.

2. Browser to get Event object differences

The first parameter of the event listener is used as the event object in DOM 2 events, and the IE Opera Chrome Safari also supports getting event objects through window.event.

Analyze the following code:

<button type= "button" id= "Attach" >attachEvent</button> <button type= "button" id= "Adde" >
addeventlistener</button> <button type= "button" id= "Byclick" >onClick</button> <br INFO: <div id= "Info" ></div> <script type= "Text/javascript" > function $ (ID) {return
	document.getElementById (ID);}

	var attach = $ ("Attach"), Adde = $ ("Adde"), Byclick = $ ("Byclick");
	Attach.attachevent && attach.attachevent ("onclick", handler);
	Adde.addeventlistener && adde.addeventlistener ("Click", Handler, false);

	Byclick.onclick = handler;
		function handler () {var src = window = = This? window.event.srcElement:this, type = src.innerhtml;
		Window.event && showmsg (window.event.type, type + "+ window.event");
	Arguments[0] && showmsg (arguments[0].type, type + "+ arguments[0]");
	function showmsg (type, msg) {$ ("info"). InnerHTML + + (type: + Type + ") <br/>");
 } </script>

The above code combines different event listener bindings and event object acquisition methods to test the level of support for each browser.

Click on ' attachevent ' >> ' addeventlistener ' >> ' OnClick ' and the results are as follows:

IE6 IE7 IE8
Chrome Safari
Opera
Firefox

The results of the test are summarized in the following table:1

How event objects are fetched IE6 IE7 IE8 Chrome Safari Opera Firefox
Window.event Y Y Y N
Arguments[0] Y2 Y Y Y

Note 1:y indicates support for this event object acquisition, N is not supported.

NOTE 2: Partial support.

As you can see from the table above:

    • Only when the event listener is registered with the Attachevent method does IE support the way in which the first parameter passed in by the event listener is used as the event object;
    • Chrome Safari Opera Two ways to get event objects are supported;
    • Firefox only supports the standard way to get event objects.

3. Differences in the properties and methods of the event objects in each browser

IE has limited support for the standard properties and methods of event objects, and for most properties and methods, IE offers an alternative to non-standard alternatives; Firefox Chrome Safari, in addition to fully supporting the standard properties and methods of event objects, also supports IE in varying degrees Non-standard alternatives provided.

The following code detects the extent to which nonstandard properties of event, Uievent, MouseEvent interfaces, and events objects are supported under browsers:

<button type= "button" id= "IEvent" >interface event</button> <button type= "button" id= "Iuimouse" > Interface uievent & mouseevent</button> <input type= "text" id= "Nosk"/> "<p id=" wrap "style=" border : 3px solid;padding:5px;width:500px; " ><a id= "NOSCM" href= "#" ></a></p> <br/> <table border= "1" > <tbody> <tr> <th>interface event</th> <td id= "Einfo" ></td> & lt;/tr> <tr> <th>interface uievent<br/>&<br/>mouseevent</th> <td id= "Minfo  "></td> </tr> <tr> <th>Non-standard<br/>&<br/>click</th> <td Id= "Ncinfo" ></td> </tr> <tr> <th>non-standard<br/>&<br/>mouseover Mouse out</th> <td id= "Nminfo" ></td> </tr> <tr> &LT;TH&GT;NON-STANDARD&LT;BR/&GT;&AMP;&L T;br/>keycode</th> <td id= "Nkinfo" ></td> </tr> </tbody> </table> <script type= "Tex
	T/javascript "> function $ (ID) {return document.getElementById (ID);} function addevent (elem, type, handler, usecapture) {Elem.addeventlistener? Elem.addeventlistener (Type, handler, Usecap
	ture): Elem.attachevent ("on" + type, handler);
	} addevent ($ ("iEvent"), "click", Handleevent, false);

	Addevent ($ ("Iuimouse"), "click", Handleuimouse, false);
	Addevent ($ ("NOSCM"), "click", Handlenosclick, false);

	Addevent ($ ("wrap"), "click", Function () {alert ("P tag.");}, False);
	Addevent ($ ("NOSCM"), "MouseOver", Handldnosmouse, false);

	Addevent ($ ("NOSCM"), "Mouseout", Handldnosmouse, false);
	Addevent ($ ("Nosk"), "KeyDown", Handlenoskey, false);
	Addevent ($ ("Nosk"), "KeyPress", Handlenoskey, false);

	Addevent ($ ("Nosk"), "KeyUp", Handlenoskey, false);
		function Handleevent (e) {e = e | | window.event; var props = {type: ' type ', target: ' Target ', CurreNttarget: "Currenttarget", Eventphase: "Eventphase", Bubbles: "Bubbles", cancelable: "Cancelable", Timesta 
		MP: "TimeStamp", Initevent: "Initevent", Preventdefault: "Preventdefault", Stoppropagation: "Stoppropagation"

		};
	ShowMsg (Props, E, $ ("Einfo"));
		} function Handleuimouse (e) {e = e | | window.event; var props = {view: "View", Detail: "Detail", Inituievent: "Inituievent", ScreenX: "ScreenX", ScreenY: "ScreenY", ClientX: "ClientX", ClientY: "ClientY", Ctrlkey: "Ctrlkey", Shiftkey: "Shiftkey", Altkey: " Altkey ", Metakey:" Metakey ", Button:" button ", Relatedtarget:" Relatedtarget ", Initmouseevent:" Initmousee
	Vent "} showmsg (Props, E, $ (" Minfo "));
		} function Handlenosclick (e) {e = e | | window.event;
		E.returnvalue = false;

		E.cancelbubble = true; var props = {cancelbubble: "cancelbubble", OffsetX: "OffsetX", OffsetY: "OffsetY", ReturnValue: "Returnva Lue ", Srcelement: "Srcelement", X: "X", y: "Y"};
	ShowMsg (Props, E, $ ("Ncinfo"));
		} function Handldnosmouse (e) {e = e | | window.event;
		var props = {fromelement: "Fromelement", Toelement: "Toelement"};
	ShowMsg (Props, E, $ ("Nminfo"));
		} function Handlenoskey (e) {e = e | | window.event;
	$ ("Nkinfo"). InnerHTML + + "<strong>" + E.type + "</strong>:" + e.keycode + "<br/>";
		function showmsg (props, E, info) {var tmp = "", p, Val;
				With (e) {to (p in props) {try{val = eval (props[p]) + "[" + typeof eval (props[p]) + "]";
				catch (e) {val = undefined;
	TMP + = "<strong>" + P + "</strong>:" + val + "<br/>"}} info.innerhtml = tmp;
 } </script>

Execute the above test code, click the ' Interface Event ' button, the ' Interface uievent & mouseevent ' button and the picture, the mouse moves to the picture to move away again, in the text box to enter ' A ', get the result to organize the following table:3

Property method
Interface & Non-standard&IE6 IE7 IE8 Chrome Safari Opera Firefox
Interface Event type Y Y Y
Target N Y Y
Currenttarget N Y Y
Eventphase N Y Y
Bubbles N Y Y
Cancelable N Y Y
TimeStamp N Y Y
Initevent N Y Y
Preventdefault N Y Y
Stoppropagation N Y Y
Interface uievent View N Y Y
Detail N Y Y
Inituievent N Y Y
Interface MouseEvent ScreenX Y Y Y
ScreenY Y Y Y
ClientX Y Y Y
ClientY Y Y Y
Ctrlkey Y Y Y
Shiftkey Y Y Y
Altkey Y Y Y
Metakey N Y Y
button Y Y Y
Relatedtarget N Y Y
Initmouseevent N Y Y
Non-standard cancelbubble Y Y Y
OffsetX Y Y N
OffsetY Y Y N
ReturnValue Y Y N
Srcelement Y Y N
X Y Y N
Y Y Y N
Fromelement Y Y N
Toelement Y Y N
KeyCode Y Y Y

Note 3:y supports the property or method on behalf of the event object, N is not supported.

As you can see from the table above:

    • IE supports all nonstandard properties of event objects, does not support all method properties and methods except ' type ' external event interface, does not support all properties and methods of Uievent interface, and does not support ' metakey ', ' relatedtarget ' properties of MouseEvent interface And the ' initmouseevent ' method;
    • Chrome Safari Opera supports all the standard and non-standard attributes and methods of event objects;
    • Firefox supports all standard properties and methods of event objects, but only ' cancelbubble ' and ' keycode ' in non-standard attributes.

It is to be noted that:

    • Firefox does not support the ' returnvalue ' property of the event object, although the ' returnvalue ' value is displayed in the test sample as false, but only because the ' returnvalue ' attribute was added to the event object and does not act as the default action to cancel the event. As you can see from the address bar, there is more ' # ', which is caused by the ' href ' attribute of a label.
    • Each browser has a different return value for the ' TimeStamp ' property of the Event interface.

For more information about the nonstandard properties and methods of the event objects that IE implements, refer to the MSDN event object.

For more information on Firefox's implementation of event objects, refer to the MDC event.

Solution

1. Use attribute judgement to create event listener bindings and binding functions without compatibility issues

Such as:

function addevent (elem, type, handler, usecapture) {
	elem.addeventlistener? elem.addeventlistener (Type, Handler, usecapture):
		elem.attachevent ("on" + type, handler);
}

function removeevent (elem, type, handler, usecapture) {
	elem.removeeventlistener? Elem.removeeventlistener (Type, Handler, Usecapture):
		elem.detachevent ("on" + type, handler);
}

2. Use characteristic to judge to obtain valid event object

In the event listener, determine if the first parameter or window.event passed in is valid, such as:

function Handler (e) {
	e = e | | window.event;
}

3. Use characteristics to judge the use of non-standard methods and attributes corresponding to the standard

Although IE has limited support for standard properties and methods of event objects, its own implementation of the event model can basically replace or implement the functionality of standard properties or methods.

The following table summarizes some of the non-standard properties that correspond to a standard event object, or that can implement standard property or method functionality:

Standard Non-standard
Target Srcelement
Preventdefault () ReturnValue
Stoppropagation () Cancelbubble
Relatedtarget Fromelement toelement

In addition, the standard ' ClientX ' properties and Non-standard ' X ' properties are the same, as are the ' ClientY ' and ' Y '.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.