Home > Article > Web Front-end > What are the exceptions for events that cannot bubble?
Exceptions for bubbling events: What events cannot bubble?
In most cases, events in web pages can be delivered and processed through the bubbling mechanism. However, in some cases, some special events cannot be bubbled. This article will introduce some common events that cannot be bubbled and provide code examples to help readers better understand.
focus
and blur
events: These two events involve focus changes of elements. When an element gains focus, the focus
event is triggered; when the element loses focus, the blur
event is triggered. Because the focus change occurs on a specific element, not its parent or other descendant elements, these two events cannot bubble up. The following is a sample code. When the input box gets focus, the event cannot be captured using bubbling events:
<!DOCTYPE html> <html> <head> <title>Focus and Blur Event</title> </head> <body> <div> <input type="text" id="myInput"> </div> <script> var myInput = document.getElementById("myInput"); myInput.addEventListener("focus", function(){ console.log("Input has focus"); }); document.body.addEventListener("focus", function(){ console.log("Focus event bubbled"); }, true); // 输出结果: // Input has focus </script> </body> </html>
In the above code, when the input box gets focus , only the focus
event will be triggered, and the focus
event that bubbles up to the body
element will not be triggered.
mouseenter
and mouseleave
events: These two events are used to detect when the cursor enters or leaves the bounds of an element. Unlike the mouseover
and mouseout
events, the mouseenter
and mouseleave
events do not bubble to parent or descendant elements. Below is a sample code, when the mouse enters or leaves the div
element, these two events cannot be captured through bubbling events:
<!DOCTYPE html> <html> <head> <title>Mouse Enter and Leave Event</title> <style> #myDiv { width: 100px; height: 100px; background-color: red; } </style> </head> <body> <div id="myDiv"></div> <script> var myDiv = document.getElementById("myDiv"); myDiv.addEventListener("mouseenter", function(){ console.log("Mouse entered the div"); }); document.body.addEventListener("mouseenter", function(){ console.log("Mouse entered the body"); }, true); // 输出结果: // Mouse entered the div </script> </body> </html>
above In the code, when the mouse enters the div
element, only the mouseenter
event will be triggered, and the mouseenter event that bubbles to the
body element will not be triggered.
event.
In summary, focus
, blur
, mouseenter
and mouseleave
events cannot be delivered through the bubbling mechanism and processing. Understanding and distinguishing these special events is one of the essential knowledge as a front-end developer.
The above is the detailed content of What are the exceptions for events that cannot bubble?. For more information, please follow other related articles on the PHP Chinese website!