Getting web front-end to combat: DOM standard html element with the IE event model difference

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/wewfdf/article/details/102632158

event

HTML element event is the internal browser automatically generated when an event occurs the html element to the outside world (mainly referring to subscribers element event) make all kinds of events, such as click, onmouseover, onmouseout and so on.

DOM event flow

DOM (Document Object Model) tree structure is a structure, when an HTML element generates an event, the event propagation path between the element and the root node, the path through which the nodes will receive the event this communication process can be called DOM event flow.

Event model major browsers

Subscription HTML element event, sent as early as before 2004, disseminate, each browser implementation is not consistent with the treatment model, until after the DOM Level3 stipulates that most major browsers only after another to support the DOM standard event model - captive and bubbling type.
In addition to the current IE browser, other mainstream Firefox, Opera, Safari all support the standard DOM event model. IE still use their own models, namely bubble type, a part of the model it is using DOM, this is also good for developers, just use the DOM standard, IE event handling are common to effective cross browser.

Bubble-type event (Bubbling)

This is achieved IE browser event model, but also the easiest to understand, at least I feel more realistic. Bubble, by definition, an event like a water bubble has to take up the same, until the top. Appreciated from the DOM tree structure, the event is passed up until the leaf node up the ancestors of the root node; is understood that the event has been a target element having a subordinate relationship to determine the most from the view HTML browser interface element level arrangement delivered to target the most uncertain element.

Capture type event (Capturing)

Achieve Netscape Navigator, which is exactly the opposite with bubble type, the topmost element from the DOM tree until the most accurate elements, the event model for developers (or at least me ...) a little hard to understand, because understanding on intuitive as it should bubbling type, the event should be delivered by the most determined elements, namely element start event occurs.
But this model is also useful in some cases, the next will be to explain.

DOM standard event model

Because the two different models has its advantages and interpretation, DOM standard supports bubble trap type and model can be said to be a combination of both of them. It can be bound in a plurality of event handlers DOM elements, and inside the processing function, this keyword is still pointing to the DOM element is bound, a further first position handler pass the event argument list of event objects.

The first is the catch-transfer event, followed by a bubble-type transfer, so if a handler both registered listeners captive events, and register event listeners bubbling type, then it will be called twice in the DOM event model .

If everyone on the program, interested in the web front end, want to learn to learn, plan to in-depth understanding of the industry friends, we can add our front-end learning buckle qun: 784,783,012 friends, whether you are a student or want to switch, I have welcomed, not Share regularly dry, finishing a web front end 2019 the latest learning materials and 0 Basics tutorial for everyone to share: learning the front we are serious

Sign up and removing event listeners

Register event listeners, also known as subscription or event, when the event occurs browser elements callback function that listens to perform event handling. There are two ways to mainstream browsers register an event, one is IE browser, the other is the DOM standard.

1. Method mounted directly or HTML JS

<``**div** onclick``=``"alert(this.innerHTML);"``>

element.onclick = **function**``(){alert(``**this**``.innerHTML);}

When removing the event property to nul can be, this is the most common method, and the advantages and disadvantages are also obvious:

  • Simple, direct writing handler code blocks in the HTML, attributes assigned to the elements corresponding event can in JS
  • A method for IE and DOM standards supported it in IE and DOM standards are in the process of bubbling event is called.
  • Can refer to elements registered in the event handler block the direct use of this
  • Give the element register multiple listeners, this method can not be used up

Register multiple event listeners and listener method removed under 2. IE

IE browser HTML elements have a attachEvent approach allows registered outside the elements of multiple event listeners, for example,

element.attachEvent(``'onclick'``, observer);

attachEvent accepts two parameters. The first parameter is the event name, the second parameter is the observer callback handler. Have to explain here, there is often the wrong place, this is no longer a point to elements previously registered event next IE use attachEvent registered handler calls, then this is the window object, and I very much wonder why so IE I do not see the benefits of lies.
To remove a previously registered event listener, call the method element of detachEvent to the same parameters.

element.detachEvent(``'onclick'``, observer);

Register multiple event listeners and listener method removed under 3. DOM standard

DOM achieve a standard browser and IE browser registered element event listeners differently, it registered through addEventListener method elements, which supports both registered bubbling type event handling, event handling and support captive.

element.addEventListener(``'click'``, observer, useCapture);

addEventListener method takes three parameters. The first parameter is the name of the event, it is noted that different events where the IE name, the name of the event is not the beginning of the 'on'; the second parameter is the callback handler observer; third parameter stating the callback process function is invoked in the event of the transfer process the capture phase or the bubbling phase is called

Remove a registered event listeners can call the element of removeEventListener, parameters unchanged.

element.removeEventListener(``'click'``, observer, useCapture);

Sign up and removing an element cross-browser event listener program

After figure out the similarities and differences between the standard and IE DOM element event listener registered, you can achieve a cross-browser and remove elements of registered event listener program:


`01.``//注册`

`02.``**function**` `addEventHandler(element, evtName, callback, useCapture) {`

`03.``//DOM标准`

`04.``**if**` `(element.addEventListener) {`

`05.``element.addEventListener(evtName, callback, useCapture);`

`06.``}` `**else**` `{`

`07.``//IE方式,忽略useCapture参数`

`08.``element.attachEvent(``'on'` `+ evtName, callback);`

`09.``}`

`10.``}`

`11.``//移除`

`12.``//注册`

`13.``**function**` `removeEventHandler(element, evtName, callback, useCapture) {`

`14.``//DOM标准`

`15.``**if**` `(element.removeEventListener) {`

`16.``element.removeEventListener(evtName, callback, useCapture);`

`17.``}` `**else**` `{`

`18.``//IE方式,忽略useCapture参数`

`19.``element.dettachEvent(``'on'` `+ evtName, callback);`

`20.``}`

`21.``}`
web前端开发学习Q-q-u-n:784783012 ,分享学习的方法和需要注意的小细节,不停更新最新的教程和学习方法(详细的前端项目实战教学视频)

How to cancel default processing after transfer event browser events pass browser

After the default processing instructions to cancel the event delivery browser event delivery are two different concepts, many students could not tell friends, or two concepts did not exist.

Cancel the event delivery means, stop capturing event type or further transfer bubbling type events. For example, the event delivery bubbling type image above, the event delivery process stops after the body, located in the upper document event listener no longer receive notifications, not processed.

After the default processing of event delivery means, usually delivered in the event browser and dealt performs the default action associated with the event (if such action exist). For example, if the form input type attribute is "submit", it will automatically submit the form completely browser event propagation click. As another example, the occurrence of input keydown event elements and processing, the browser will default characters typed by the user is automatically added to the value of the input element.

To cancel the transfer pieces of the browser, IE and DOM standards are different.

In IE, by setting the event object to cancelBubble is true.

1.``**function** someHandle() {

2.``window.event.cancelBubble = **true**``;

3.``}

DOM standard event object by calling stopPropagation () method can be.

1.``**function** someHandle(event) {

2.``event.stopPropagation();

3.``}

Because some, ways to stop cross-browser event delivery are:

1.``**function** someHandle(event) {

2.``event = event || window.event;

3.``**if**``(event.stopPropagation)

4.``event.stopPropagation();

5.``**else** event.cancelBubble = **true**``;

6.``}

The default treatment after delivery to cancel the event, IE and DOM standards do not differ.

In IE, by setting the event object returnValue is false.

1.``**function** someHandle() {

2.``window.event.returnValue = **false**``;

3.``}

DOM standard method to object by calling the event preventDefault ().

1.``**function** someHandle(event) {

2.``event.preventDefault();

3.``}

Because some, the default post-processing method of cross-browser event delivery is canceled:

1.``**function** someHandle(event) {

2.``event = event || window.event;

3.``**if**``(event.preventDefault)

4.``event.preventDefault();

5.``**else** event.returnValue = **false**``;

6.``}

Captive bubble-type event model and event model applications

Standard event model provides us with two options, many of my friends tell two different models so what benefits, why not just adopt a model.
Here aside to discuss the IE browser (IE only one, no choice) Which event model fit under what circumstances.

1. Capture type applications

Captive events delivered by the most imprecise ancestor element has been the most accurate source of event elements, delivery methods and operating systems global shortcuts and application shortcuts similar. When a system key combinations happen if the system is registered global shortcuts listener, the event will first be captured operating system layer, global listeners will first be notified of the application shortcuts listener, which is a global first gain control right, it has the right to prevent further transfer events. Therefore captive listener event model suitable for use as the global scope, here is the global overall opposite, with respect to a certain range of the set top junction formed by the junction point and all descendant nodes.

For example, you want to make a global click event listener, with respect to all child nodes under document node with the document, it requires that all child nodes under certain conditions invalid clicks, bubble model in this case will not be solved, the capture type is very suitable, you can add event listeners captive at the top level nodes, pseudo-code as follows:


`2.``**if**``(canEventPass ==` `**false**``) {`

`3.``//取消事件进一步向子结点传递和冒泡传递`

`4.``event.stopPropagation();`

`5.``//取消浏览器事件后的默认执行`

`6.``event.preventDefault();`

`7.``}`

`8.``}`

As a result, when canEventPass condition is false, document all child nodes click event registration will not be processed browser.

2. The bubble-type applications

We can say that we usually use are bubbling event model, because this model only supports IE. Here still talk about, in the proper use of the model can improve the performance of the script. In some elements of the event triggering frequent, as onmousemove, onmouseover, onmouseout, if not necessary to further define the event handler passed, then you can boldly to cancel it. In addition, the parent will have to deal with a child node layer listeners event listener processing negative impact should also be prohibited in the event passed up further sub-node listener to remove.

Comprehensive Case Study

Finally, the HTML code for the following analysis:

01.``<``**body** onclick``=``"alert('current is body');"``>

02.``<``**div** id``=``"div0" onclick``=``"alert('current is '+this.id)"``>

03.``<``**div** id``=``"div1" onclick``=``"alert('current is '+this.id)"``>

04.``<``**div** id``=``"div2"``>

05.``<``**div** id``=``"event_source"

06.``onclick``=``"alert('current is '+this.id)"

07.``style``=``"height:200px;width:200px;background-color:red;"``>

08.``</``**div**``>

09.``</``**div**``>

10.``</``**div**``>

11.``</``**div**``>

12.``</``**body**``>

After running the HTML click the red zone, which is the innermost layer of DIV, according to the instructions above, both the DOM standard or IE, written directly in html listening handler is called when the event bubbling passed by the innermost layer has to on the transfer, it will have been a
Current IS event_source
Current IS div2
Current IS div1
div0 Current IS
Current IS body

Add the following snippet:

1.``**var** div2 = document.getElementById(``'div2'``);

2.``addEventHandler(div2, 'click'``, **function**``(event){

3.``event = event || window.event;

4.``**if**``(event.stopPropagation)

5.``event.stopPropagation();

6.``**else** event.cancelBubble = **true**``;

7.``}, **false**``);

When you click the red zone, according to the instructions above, during the bubble bubble up, after the event delivery div2 to stop delivering, so div2 upper element not receive notification, it will have appeared:
Current IS event_source
Current IS div2

In support DOM standard browser, add the following code:

1.``document.body.addEventListener(``'click'``, **function**``(event){

2.``event.stopPropagation();

3.``}, **true**``);

The above code listener function because it is being called when captive transfer, so click the red zone, though the event source is the ID for the event_source elements, but captive election passed, start from the top, body node monitor function is first call and cancel the event passed down further, it will only be current is body

Guess you like

Origin blog.csdn.net/wewfdf/article/details/102632158