Example Analysis of event capture in JavaScript
This article mainly introduces the example analysis of event capture in JavaScript, which is very detailed and has certain reference value. Friends who are interested must finish it!
What is event capture?
When an event occurs on a DOM element, the event does not happen exactly on that element. In the capture phase, the event starts at window and goes all the way to the element that triggers the event. Window---- > document---- > html---- > body-> Target element
Suppose you have the following HTML structure:
one
Corresponding JS code:
Function addEvent (el, event, callback, isCapture = false) {if (! el | |! event | |! callback | | typeof callback! = = 'function') return; if (typeof el =' string') {el = document.querySelector (el);}; el.addEventListener (event, callback, isCapture);} addEvent (document, 'DOMContentLoaded', () = > {const child = document.querySelector (' .child'); const parent = document.querySelector ('.parent'); const grandparent = document.querySelector ('.grandparent') AddEvent (child, 'click', function (e) {console.log (' child');}); addEvent (parent, 'click', function (e) {console.log (' parent');}); addEvent (grandparent, 'click', function (e) {console.log (' grandparent');}); addEvent (document, 'click', function (e) {console.log (' document');}) AddEvent ('html',' click', function (e) {console.log ('html');}) addEvent (window,' click', function (e) {console.log ('window');})})
The addEventListener method has a third optional parameter, useCapture, whose default value is false, and the event will occur during the bubbling phase or, if true, during the capture phase. If you click the child element, it will print window,document,html,grandparent and parent on the console, respectively, which is called event capture.
The above is all the content of the article "sample Analysis of event capture in JavaScript". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!