Detailed explanation of event bubbling and preventing event bubbling

What is event bubbling?

Event bubbling: trigger from child element to parent element—>When an event is triggered, the same event will be triggered to the parent element.
But not all events will produce bubbling problems. Onfocus, onblur, and onload will not produce bubbling problems. The
above text seems too official and not easy to understand. Here are some easy-to-understand
examples to illustrate:
For example:
Now on the window There is a button, bind a click event to the button, and click the button to display a prompt box.
Bind a click event to the interface, click anywhere outside the button to make the prompt box disappear.
So the problem is that the buttons belong to the interface too. Wouldn't it be a conflict if you click the button. So how to solve this problem?

This type of situation is called event bubbling!
Insert picture description here

Stop event bubbling

Where can I stop the incident from bubbling?
Preventing incidents from bubbling up is like, a certain part of a person's body has a disease and may spread to other parts, we need to perform surgery on this part to prevent it from spreading.

Insert picture description here

html code:

 <input type="button" value="按钮" id="obut" onclick="but()">
 <div id="div1" style="display: none;width: 300px; height: 100px; border: 1px solid black;">提示框</div>

javascript code:

 let obut = document.getElementById("obut");
 let div1 = document.getElementById("div1");
   function but(evt){
        let e = evt || event; //为了兼容大多数浏览器 这里采用事件的兼容写法
        div1.style.display = "block"; //点击安钮让其提示框显示
        e.stopPropagation?e.stopPropagation():e.cancelBubble=true;//阻止事件冒泡
    }
    document.onclick = function(){//给document绑定点击事假
        div1.style.display = "none";//点击界面的任何一个位置让提示框隐藏
    }

Guess you like

Origin blog.csdn.net/qq_43923146/article/details/107472291