Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize event bubbling and time capture in JavaScript

2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you how to achieve event bubbling and time capture in JavaScript. I hope you will gain something after reading this article. Let's discuss it together.

Event bubbling and event capture

When we click on an element on the Web page, such as a p element. When you think about it, we click not only on this p element, but also on the concentric circle elements with the p as the center, such as the parent of the element, the outer body, the parent element of body, html, and the outer document. The propagation of events between these nested elements is called an event flow.

1. Event bubbling

2. Event capture

1. Event bubbling

IE's event flow is called event bubbling, and events start with the most specific elements and propagate up step by step. The event handlers we added using DOM0 are handled during the event bubbling phase. For example:

_ window.onload = bubblingHandle; function bubblingHandle () {/ / inner p handler document.getElementById ("inner"). Onmousedown = function () {alert ("inner p");} / / outer p handler document.getElementById ("outer"). Onmousedown = function () {alert ("outerp") } _ document.onmousedown = function () {alert ("document");}}-- >

When you click the white p in the inner layer, it will be displayed in turn:

Inner pouter pdocument

Event capture

Netscape's event flow is called event capture, which is almost the opposite of IE. Events are first received by the least specific elements and then propagated to specific nodes step by step.

II. DOM0 level event handling

Event, triggered by some specific behavior that occurs in the WEB page. For example, pressing the left mouse button on a page element and pressing a key on the keyboard will trigger the corresponding event when an object gains or loses focus. The interaction between JavaScript and HTML is achieved through events. We use event listeners to "register" events and execute the corresponding code when they occur.

DOM0-level event handlers are still supported by all browsers because of their simplicity and cross-browser support.

Specify event handlers through DOM0-level methods

This in event handlers

Delete event handlers through DOM0-level methods

Specify event handlers through DOM0-level methods

Specifying the event handler method through the DOM0-level method is simple, first taking a reference to the element to be manipulated, and then assigning a function to the corresponding event handler property of that element. Each element, including window and document, has its own event handler properties. Note that the event handlers added by this method will be handled during the bubbling phase of the event flow

With regard to event handler properties, there are the following points to explain:

1. Event handler properties are all lowercase, starting with "on", followed by the event type:

Onclick / / Click the mouse onload / / Image or page load complete onmouseover / / move the mouse over an element onmousemove / / move the mouse onfocus / / object to get focus

2. Each element, such as img, a, input, form, including window and document, has its own event handler properties. Such as:

Document.getElementById ("btn1"). Onclick / / btn1 click document.getElementById ("img1"). Onmouseover / / move the mouse to img1document.getElementById ("img1"). Onmerror / / img1 image cannot be loaded

Next, assign a value to the event handler property to complete the assignment of the event handler method. For example, when the mouse moves over "img1", the dialog box "This is a nice pic!" pops up:

Var pic1 = document.getElementById ("img1"); pic1.onmouseover = function () {alert ("This is a nice pic!");}

Special note: if the above code is at the bottom of the document, we move the mouse over the img1 when the page is just loaded. It is possible that the dialog box we set will not pop up because the code has not yet been executed! Today, the delay is very short.

This in event handlers

An event handler specified by a DOM0-level method, belonging to an element method. Therefore, our this in the event handler refers to this element! Illustrate through the following examples:

... / omit deleting event handlers through DOM0-level methods

To delete an event handler, simply set the corresponding event handler property to null:

Pic1.onmouseover = null; III, DOM2 level event handling 1, addEventListener and removeEventListener

Currently, almost all browsers support the DOM0 event model, but developers are encouraged to use the new DOM2 model. There are two significant differences between the DOM2 model and DOM0:

1. DOM2 does not depend on event handler properties

2. Multiple handlers can be registered for the same event of the object at the same time, and they are executed in turn according to the registration order.

DOM2 defines two methods:

AddEventListener () / / specify event handler removeEventListener () / / delete event handler

All DOM nodes contain these two methods, both of which take three parameters, the first to handle the event name (excluding on), the second event handler, and the third Boolean variable:

For example, we add two event handlers for the click event of the button btn1, and the event handler is handled during the event bubbling phase:

...

When you click the btn1 button, the dialog box pops up in turn:

Handle1!handle2!

We can use the removeEventListener () method to delete the event handler we just specified, and note that the parameters are consistent:

Btn1.removeEventListener ("click", handle2, false)

When you click the btn1 button at this point, only handle1! is displayed.

In particular, if we use anonymous functions to specify event handlers, we cannot delete event handlers using the removeEventListener () method:

Btn1.addEventListener ("click", function () {alert ("click!");}, false); btn1.removeEventListener ("click", function () {alert ("click!");}, false); / / cannot be cancelled!

It is impossible to cancel the event handler specified above! Because the two event handlers in addEventListener and removeEventListener above are essentially two different function references, although they have the same code.

In addition, to emphasize that the first parameter of the above two functions (the name of the event to be handled) does not have an on prefix. This is different from IE, which will be explained later.

Tips: IE9, Firefox, Safari, Chrome, and Opera all support DOM2 level event handlers.

This in the DOM2 event handler

DOM2 event handlers are the same as DOM0, and their this runs in the element scope on which they are attached. The reference of this refers to an example of DOM0. The this of DOM2 is specifically noted here to distinguish it from the IE event handler. The event handler this in IE is related to how the event is specified.

4. IE event handler and cross-browser support for attachEvent () and detachEvent ()

IE does not provide support for the W3C event model, which implements two methods similar to the DOM2 model:

AttachEvent () detachEvent ()

These two methods receive only two parameters: the event name and the event handler. Since IE8 and earlier versions only support event bubbling, the event handlers added by these two methods are executed during the event bubbling phase.

Unlike DOM2, it is:

1. The running scope of IE event handling method is global, and this refers to window.

2. The name of the first parameter event is prefixed with on

3. When multiple handlers are specified for the same event of the same object, the order of execution is the opposite of that of DOM2, and the reverse order is executed in IE in which they are added.

For example:

...

Execution result:

Handle2percent truehandle1 true cross-browser support

Although we can use JS libraries that shield browser differences, in fact, it is not difficult for us to write our own cross-browser compatible event handling code, and it is more beneficial for us to learn and understand native JavaScript. We use an object traditionally called EventUtil for cross-browser event handling:

Var EventUtil = {addEventHandler: function (element, eventType, handler) {if (element.addEventListener) {element.addEventListener (eventType, handler, flase);} else if (element.attachEvent) {element.attachEvent ("on" + eventType, handler);} else {element ["on" + eventType] = handler }, removeEventHandler: function (element, eventType, handler) {if (element.aremoveEventListener) {element.addEventListener (eventType, handler, flase);} else if (element.detachEvent) {element.attachEvent ("on" + eventType, handler);} else {element ["on" + eventType] = null;}

To ensure that the event handling code runs consistently in most browsers, we only focus on the bubbling phase here. The above code uses browser capability detection to first detect whether the DOM2-level methods addEventListener and removeEventListener are supported, and use this method if it is not supported; if not, detect whether it is an earlier version of the IE8-level attachEvent or detachEvent method, and use this method if it is supported; if neither of the above two methods is supported, use the DOM0-level method. Note that the DOM0 level can only specify one event handler per event.

Examples of the above objects are as follows:

Var btn1 = document.getElementById ("btn1"); var handle1 = function () {alert ("handle1!" + "\ n" + (this = window));}; var handle2 = function () {alert ("handle2!" + "\ n" + (this = window));}; EventUtil.addEventHandler (btn1, "click", handler1); EventUtil.addEventHandler (btn1, "click", handler2); EventUtil.removeEventHandler (btn1, "click", handler2); 5. Event object

When an event is triggered, an event object is generated. This object contains information about the event. For example, the element that triggers the event, the type of event, and something related to a specific event, such as mouse position information, and so on.

1. DOM event object

2. IE event object and cross-browser event object

1. DOM event object

Whether you specify an event handler using DOM0-level or DOM2-level methods, an event object is automatically passed into the event handler when the event is triggered, for example:

Var btn1 = document.getElementById ("btn1"); btn1.onmouseover = function (evnt) {alert (evnt.type);} var handle = function (evnt) {alert (evnt.type);}; btn1.addEventListener ("click", handle, false)

The above is an example of a simple event object. The type property in the event object is a read-only string property that contains the type of event. For example, click and onmouseover in our previous example. The event object contains a large number of properties and methods related to the event (for example, the event.stopPropagation () method can be used to stop the event from continuing to propagate during the capture or bubbling phase, and the preventDefault () method unblocks the rows that block the event.) it is not listed here. The commonly used ones are as follows:

Property / method value type read / write describes the target typeStringreadonly event type of the element targetElementreadonly event currently being processed by the currentTargetElementreadonly event handler preventDefaultFunctionreadonly cancel event default behavior, such as the default behavior of a link is to jump to the urlstopPropagationFunctionreadonly cancellation event specified by href when clicked to further bubble or capture 2, IE event object and cross-browser event object IE event object

In IE, when you specify an event handler at the DOM0 level, the event object is considered a property of window, such as the code that gets the mouse click coordinates:

Var mouseLoc = function () {var loc = "x:" + window.event.screenX + "\ n" + "y:" + window.event.screenY; alert (loc);}

When you specify an event handler using the attachEvent () method, the event object is passed into the event handler as a parameter, and we rewrite the above code:

Var mouseLoc = function (event) {var loc = "x:" + event.screenX + "\ n" + "y:" + event.screenY; alert (loc);}; btn1.attachEvent ("onclick", mouseLoc)

Related property methods of the event object in IE:

Property / method value type read-write description cancelBubbleBooleanread/ write defaults to false, cancel event bubbling when set to true (same as stopPropagation in DOM) returnValueBooleanread/ write defaults to true, set to false cancellation event default behavior (same as preventDefault in DOM) srcElementElementreadonly event target typeStringreadonly event type cross-browser event object

The idea of solving the cross-browser problem is consistent. We can test the capability of the browser. Here we extend the above EventUtil object and learn about native JS, which is a very beautiful object:

Var EventUtil = {addEventHandler: function (element, eventType, handler) {if (element.addEventListener) {element.addEventListener (eventType, handler, flase);} else if (element.attachEvent) {element.attachEvent ("on" + eventType, handler);} else {element ["on" + eventType] = handler }, removeEventHandler: function (element, eventType, handler) {if (element.aremoveEventListener) {element.addEventListener (eventType, handler, flase);} else if (element.detachEvent) {element.attachEvent ("on" + eventType, handler);} else {element ["on" + eventType] = null }}, getEvent: function (event) {return event? Event: window.event;}, getTarget: function (event) {return event.target | | event.srcElement;}, preventDefault: function (event) {if (event.preventDefault) {event.preventDefault ();} else {event.returnValue = false }, stopPropagation: function (event) {if (event.stopPropagation) {event.stopPropagation ();} else {event.cancelBubbles = true;}}, getRelatedTarget: function (event) {if (event.relatedTarger) {return event.relatedTarget;} else if (event.toElement) {return event.toElement } else if (event.fromElement) {return event.fromElement;} else {return null;}} after reading this article, I believe you have a certain understanding of "how to achieve event bubbling and time capture in JavaScript". If you want to know more about it, welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report