Learn how to use bubbling events to achieve interactive effects: Example analysis of JS bubbling events

PHPz
Release: 2024-01-13 08:09:06
Original
698 people have browsed it

Learn how to use bubbling events to achieve interactive effects: Example analysis of JS bubbling events

JS bubbling event example analysis: To master how to use bubbling events to achieve interactive effects, specific code examples are needed

With the development of the Internet, JavaScript (JS) has become An important technology in front-end development. In front-end development, JS bubbling events are often used to achieve interactive effects. This article will introduce the basic concepts and usage of JS bubbling events through specific code examples, and analyze how to use bubbling events to achieve some common interactive effects.

1. Basic concepts of JS bubbling events
In HTML documents, the element structure is often a nested relationship. When an element triggers an event, the event is propagated (bubbled) up to the parent element until it reaches the document root element. This is the basic concept of JS bubbling events. Bubbling events include common click events, mouse move-in and move-out events, keyboard events, etc.

2. Specific usage of bubbling events

  1. Create HTML structure
    First, we need to create some HTML elements with nested relationships to demonstrate the bubbling events transfer process. For example, create a div container and add several div elements inside the container. The code is as follows:
元素1
元素2
元素3
Copy after login
  1. Add JS code
    Next, we need to add some JS code for These elements are bound to event listeners so that you can observe the event bubbling up. The code is as follows:
var container = document.getElementById('container'); var elements = container.getElementsByTagName('div'); // 为每个元素绑定事件监听器 for (var i = 0; i < elements.length; i++) { elements[i].addEventListener('click', function(event){ console.log('当前元素:', event.target.innerHTML); console.log('冒泡元素:', getBubblingElements(event)); }); } // 递归获取所有冒泡元素 function getBubblingElements(event) { var bubblingElements = []; var currentElement = event.target; while (currentElement !== document) { bubblingElements.push(currentElement.innerHTML); currentElement = currentElement.parentNode; } return bubblingElements; }
Copy after login

In the code, we first obtain the container element and its sub-elements, and then bind a click event listener to each sub-element. When a child element is clicked, the listener prints out the contents of the current element and all bubbled elements.

  1. Testing bubbling events
    Finally, we can test the delivery process of bubbling events by clicking on the div element. When we click on a div element, the console will output the contents of the currently clicked element and all bubbling elements. For example, if element 3 is clicked, the output result is as follows:
当前元素: 元素3 冒泡元素: [元素3, 元素2, 元素1, #container]
Copy after login

The above results indicate that the actual element clicked is element 3, and the bubbling process passes through element 2, element 1 and the container element in sequence. (#container).

3. Use bubbling events to achieve interactive effects
After mastering the basic concepts and specific usage of bubbling events, we can use bubbling events to achieve some common interactive effects. The following takes the cancellation of bubbling, event proxy and event delegation as an example for analysis.

  1. Cancel bubbling
    Sometimes, we want an event to be executed only on the current element without being passed to the parent element. At this time, you can use the stopPropagation method of the event object to cancel the bubbling of the event. For example, we modify the above code so that only the content of the currently clicked element will be output to the console:
// 为每个元素绑定事件监听器 for (var i = 0; i < elements.length; i++) { elements[i].addEventListener('click', function(event){ console.log('当前元素:', event.target.innerHTML); console.log('冒泡元素:', getBubblingElements(event)); event.stopPropagation(); // 取消事件冒泡 }); }
Copy after login

In the modified code, the stopPropagation method of the event object is added and called in the listener This method can cancel the bubbling delivery of events. In this way, when a div element is clicked, only the current element and its content will be output to the console.

  1. Event proxy
    When there are many DOM elements that need to be bound to the same event listener, you can use event proxy to simplify the code. By binding the event listener to the parent element and using the bubbling event delivery process, the event of the child element is captured on the parent element. For example, we modify the above code to bind the event listener to the container element:
container.addEventListener('click', function(event){ if (event.target.tagName === 'DIV') { // 只处理div元素的点击事件 console.log('当前元素:', event.target.innerHTML); console.log('冒泡元素:', getBubblingElements(event)); } });
Copy after login
Copy after login

In the modified code, bind the event listener to the container element and add the In the code, it is determined that the div element is clicked by judging the tagName of event.target. This way, no matter how many div elements we add to the container, we only need one event listener.

  1. Event delegation
    Event delegation is a way to efficiently utilize bubbling events. You can place a certain type of event listener on the parent element and proxy all child elements of that type. event. For example, we modify the above code and only add a click event listener for the container element to proxy the click events of all div elements:
container.addEventListener('click', function(event){ if (event.target.tagName === 'DIV') { // 只处理div元素的点击事件 console.log('当前元素:', event.target.innerHTML); console.log('冒泡元素:', getBubblingElements(event)); } });
Copy after login
Copy after login

In the modified code, only a click is added for the container element Event listener, and determine whether the tagName of event.target is a div element in the listener code. In this way, no matter how many div elements we add to the container, they will be processed by the event listener proxy.

Summary:
This article introduces the basic concepts and usage of JS bubbling events through specific code examples, and analyzes in detail how to use bubbling events to achieve some common interactive effects, including canceling bubbling. , event proxy and event delegation. Mastering the use of bubbling events can improve the efficiency of interactive effects in front-end development and provide web users with a better user experience. I hope this article will help readers understand and apply JS bubbling events.

The above is the detailed content of Learn how to use bubbling events to achieve interactive effects: Example analysis of JS bubbling events. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!