1. DOM and DOM events
DOM refers to the DOM document object model, which starts with the root element and expands into a tree that describes the methods and interfaces used to process web content. The most fundamental object is document (window.document). What is a DOM event? For example, click is an event that can be followed by a binding function to perform a function. Events can be triggered in any part of the Document structure, either by user action or by the browser itself. Events are not just triggered and terminated in one place; They flow through the document and have their own life cycle.
2. What is capture and what is bubbling?
The DOM event model itself explains that elements have a binding function execution order. From the figure we can see the three phases in the event model (executed in sequence) 1. Capture phase 2. Target stage 3. Bubble stage
-
In which order? This can be controlled by the third parameter of addEventListener
-
E.adddeventlisenter (‘click’,f2,true) // true executes the function in the capture direction
-
E.adddeventlisenter (‘click’,f2,false) // false executes function in bubble direction
-
E.toppropagation () can interrupt bubbling. Generally used to encapsulate some independent components.
-
E.preventdefault () is to cancel the default event.
3. Differences between Target and currentTarget
- Target is the element that the user clicks on
- CurrentTarget is an element that the programmer listens on
<span> Text </span> </div>Copy the code
E. arget is a span
E.c. with our fabrication: urrentTarget is div
4. How do I customize events?
In addition to the more than 100 events that come with the browser, programmers can also define some of their own;
<div> <button id="button1"></button> </div> button1.addElementListener('click',()=>{ const event = new CustomEvent('huo',{detail:{name:'huo',age:2}}) The event name and event information for the dispatchEvent (event). / / the event triggered}) for the addElementListener (' re-arrest -- '(e) = > {the console. The log (e.d etail) / / to monitor this event })Copy the code
5. What is event delegation?
Event delegate is to listen for the ancestor element, and when we click it, we will determine whether it is the element we want to listen for. If it is, we will execute the function. The advantage of event delegate is that it saves memory and can listen for dynamic elements.
The complete encapsulation code is as follows:
function on(eventType,element,selector,fn){ if (! (element instanceof Element)){ element = document.querySelector(element) } element.addEventListener(eventType,(e)=>{ let t = e.target while(t.tagName.toLowercase() ! == selector){ if(t === element){ t = null break } t = t.parentNode } t && fn.call(t,e,t) }) return element }Copy the code
Article Reference:
-
DOM event model or DOM event mechanism
-
DOM event model and event delegate