In JavaScript Dom operation will definitely encounter JS bubbling event, most commonly is the div pop-up window event solution
When clicking on the gray part of the pop-up window disappears, clicking on the Black section has no effect.
The following section of code to analyze the bubbling event JS
HTML code:
<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"> <title>JS Bubbling Event</title> <Linkrel= "stylesheet"href= "Style.css"></Head><Body> <Divclass= "Container"> <H1>JS Bubbling Event Analysis</H1> <HR> <Divclass= "box Bg-gray"> <Buttonclass= "BTN">Click me! </Button> </Div> </Div> <Script> varBox=Document.queryselector (". Box"), BTN=Document.queryselector (". BTN"); Box.onclick=function(Event) {alert ("I'm the div ."); } Btn.onclick=function(Event) {alert ("I'm the button ."); } </Script></Body></HTML>
View Code
Look again effect: http://2.liteng.sinaapp.com/javascript/starevent.html
Using the 3d view of the default developer tool in the Firefox browser, you can clearly see the order of div layers
Graphic:
When the button is clicked, the "I Am Button" pops up and "I am div", because the next div Click event is triggered by triggering the button event first.
The triggering of events is the FIFO principle.
Graphic:
Then there are times when we don't want to trigger a conflict with multiple events, so the event has stoppropagation (); method to prevent bubbling
There is also an event method is more commonly used such as a link, click on the link when I do not want to jump, then use Event.preventdefault ();
The instance code is as follows
<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"> <title>JS Bubbling Event</title> <Linkrel= "stylesheet"href= "Style.css"></Head><Body> <Divclass= "Container"> <H1>JS Bubbling Event Analysis</H1> <HR> <Divclass= "box Bg-gray"> <Buttonclass= "BTN">Click me! </Button> <ahref= "http://www.liteng.org"ID= "link">I am a link</a> </Div> </Div> <Script> varBox=Document.queryselector (". Box"), BTN=Document.queryselector (". BTN"); Box.onclick=function(Event) {alert ("I'm the div ."); } Btn.onclick=function(Event) {alert ("I'm the button ."); Event.stoppropagation (); } document.getElementById ('Link'). onclick=function(Event) {alert ("I'm link ."); Event.preventdefault (); } /*differentiate Event.stoppropagation (); and Event.preventdefault (); The former uses the Stoppropagation () method to prevent event bubbling, which is to block the default behavior, such as blocking hyperlinks*/ </Script></Body></HTML>
Click to see the final effect: http://2.liteng.sinaapp.com/javascript/event.html
Original address: Http://liteng.org/node/37
JavaScript Bubbling Event Analysis