Js analysis for understanding the event bubbling

A. Events

  1. Three phases of the event: Event Capture -> Event target -> event bubbling
  • Capturing phase: first by the root document document objects to trigger events, event object is captured from the outside;
  • Phase goal: to reach the target event location (the incident), a trigger event;
  • Bubbling phase: re-orientation of the document back to the root node of the event location from the target, bubbling event object from the inside out
  1. Event Capture : First place in the document when an event occurs, followed by transfer to the body, and finally reach the destination node (ie, the event target), the event flow model: body div → → → HTML document .

  2. Event bubbling : not the end of the event after event to reach the target, it will bubble up layer by layer, until the document object, capturing the event with the opposite.

  3. onclick event bubbling, rewrite before onlick will cover the property, there is no compatibility issues

  • addEventListener(event.type, handle, boolean);IE8 and below is not supported, the method belongs DOM2 stage, a plurality of methods may be added is not covered. Event type is not on, the third parameter false, indicating that the event triggering the third phase (bubble), true trigger event represents the first stage (capture). If you bind the same event with a method, only once, so if the handle is the same method, is performed only once.
  • attachEvent(event.type, handle ); IE-specific, compatible with IE8 and below, you can add multiple event handlers, only supports bubbling phase, which can bind many times, so if the handle is the same method, bindings perform several times, while the type of event to add on.
  • Default event behavior: = "" links, submit form submit, href
  1. Prevent the default event :
  • return false; Exclusive property to prevent the default event (through on this way) binding event, preventing the browser default handling of the incident, only valid in the current function, will not affect the implementation of other external functions
  • event.preventDefault( );
  • Stop by addEventListener( )the default event to add an event event.returnValue = false;to stop by attachEvent( )the default event added events
  1. Unbundling binding event event

    Event bindings :

    code show as below:

 function addEvent(element,eType,handle,bol){
        // 支持addEventListener if(element.addEventListener){ element.addEventListener(eType,handle,bol); // 支持attachEvent }else if(element.attachEvent){ element.attachEvent("on"+eType,handle); // 兼容的onclick的绑定 }else{ element["on"+eType] = handle; } }

De-tie events :

code show as below:

function removeEvent(element,eType,handle,bol){
        // 支持addEventListener if(element.addEventListener){ element.addEventListener(eType,handle,bol); // 支持attachEvent }else if(element.attachEvent){ element.detachEvent("on"+eType,handle); // 兼容的onclick的绑定 }else{ element["on"+eType] = null; } }

Wrapper function: event bubbling by way compatible event capture only need to add a parameter bool

code show as below:

 var EventUtil = {
         addEvent: function(element,type,handle){ if(element.addEventListener){ element.addEventListener(type,handle,false); }else if(element.addEvent){ element.addEvent("on"+type,handle); }else{ element["on"+type] = handle; } }, removeEvent:function(element,type,handle){ if(element.removeEventListener){ element.removeEventListener(type,handle,false); }else if(element.removeEvent){ element.removeEvent("on"+type,handle); }else{ element["on"+type] = null; } } }
  1. Common event binding

1)bind()

  • It can only be invoked when the element to an already existing binding event, can not bind future events to the new element
  • Situation can not use bind (): bind the same event as many elements in the DOM, the element binding events do not yet exist in the DOM

2)live()

  • The method will click event bound to $(document)an object, but just give $(document)binding once and then be able to handle subsequent node dynamically loaded event
  • Upon receiving any event, $(document)the object will check the event type and target event, if the event is a click event and the goal is td, then the implementation entrusted to its handler

3)delegate()

  • Directly to the target element selectors ( "td"), event ( "click") and handling procedures and "dragged by the party" $("#info_table")binding, not the collection of additional elements, event propagation paths shortened, semantic clear
  • Support calls at the back of consecutive DOM traversal methods that support $("table").find("#info").delegate...,supports accurate control
  1. Event bubbling, event capture stop
  • event.stopPropagation( ); Prevent the further spread of events, including (bubble, capture), no parameters
  • event.cancelBubble = true; true to prevent bubbling
  1. Any incident W3C event model, starting with its ancestor window to start capturing all the way down until it reaches the target element, and thereafter began to bubble from the target element again. May decide to event handlers are registered in the capture or bubbling phase.

Note: If the last parameter of addEventListener is true, then the handler will be triggered during the capture phase; otherwise (false), it would be triggered in the bubbling phase, default false.

Second, the event bubbling

  1. Event bubbling : When an element receives an event he received event will pass their parent until the window. From the event source, bottom-up process, preventing bubble up that prevent the parent element of the triggering event is triggered when the parent elements do events trigger on this event source is invalid. In the course of the event spread, when after starting the event on an element, the event will progressively spread to the ancestors element until the document, some browsers may until window.

  2. Examples of event bubbling

    code show as below:

<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>事件冒泡</title> </head> <body> <div id="div1">div1 <div id="div2">div2</div> </div> </body> <script> var div1 = document.getElementById("div1"); var div2 = document.getElementById("div2"); div1.onclick = function(){ console.log("我是div1"); }; div2.onclick = function(){ console.log("我是div2"); }; </script> </html>

Description: div1 and div2 two parent-child relationships, are bound to div1 and div2 click event. When you click div1 when the console printout I was div1. When you click div2 when the console printout I was div2 and I was div1, at this time when we explained when the child clicks div2, div1 the event is also triggered, the parent event is triggered, this phenomenon is quite in is a bubbling event.

  1. Cancel event bubbling way :
  • W3C standard way: e.stopPropagation();here stopPropagationis a standard method of the event object, you can call
  • Non-standard IE way: ev.cancelBubble=true;here cancelBubbleis the property of IE event object, it is set to true

Cancel function package event bubbling :

code show as below:

function stopBubble(env){
        // 如果提供事件对象,说明为非IE浏览器 if(env && env.stopPropagation){ env.stopPropagation(); }else{ // IE浏览器 window.event.cancelBubble = true; } }
  1. Examples cancel event bubbling :

    code show as below:

<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>事件冒泡2</title> <style> .d1 { width: 300px; height: 300px; background-color: skyblue; display: none; } </style> </head> <body> <button id="btn">按钮</button> <div class="d1"></div> </body> <script> // 单击动作会从btn传到document中,发生事件冒泡 var btn = document.getElementById("btn"); var d1 = document.getElementsByClassName("d1")[0]; // 点击按钮的时候,元素d1显示 btn.onclick = function(e){ d1.style.display = "block"; // 阻止冒泡 stopBubble(e); }; // 点击网页其它地方的时候,元素d1隐藏 document.onclick = function(){ d1.style.display = "none"; }; // 阻止浏览器的默认行为函数,事件冒泡 // event.stopPropagation 阻止事件冒泡的方法 function stopBubble(e) { // 非IE浏览器阻止冒泡 if( e && e.stopPropagation ) e.stopPropagation(); else // IE浏览器阻止冒泡 window.event.cancelBubble = true; } </script> </html>

Description: Definition of a button, the buttons below have a div element d1, hidden by default. Click the button, the display elements d1. After clicking the button, call the function stopBubble prevent the occurrence of an event bubbling (). Click docume page elsewhere when elements d1 hidden.

Third, cross-browser event object

  1. Cross-browser event object

    code show as below:

    var EventUtil={
    getEvent:function(event){ return event||window.event; }, getTarget:function(event){ return event.target||event.srcElement; }, preventDefault:function(){ if(event.preventDefault){ event.preventDefault(); }else{ event.returnValue=false; } }, stopPropagation:function(){ if(event.stopPropagation){ event.stopPropagation(); }else{ event.cancelBubble=true; } }, addEvent:function(element,type,handler){ if(element.addEventListener){ element.addEventListener(type,handler,false); }else if(element.attachEvent){ element["e"+type]=function(){ handler.call(element) } element.attachEvent("on"+type,element["e"+type]); }else{ element["on"+type]=handler; } }, removeEvent:function(element,type,handler){ if(element.removeEventListener){ element.removeEventListener(type,handler,false); }else if(element.detachEvent){ element.detachEvent("on"+type,element["e"+type]); element["e"+type]=null; }else{ element["on"+type]=null; } } };

 

Guess you like

Origin www.cnblogs.com/feifan1/p/11358451.html