In the event of a click, determine whether the object (E.target) is a parent element (which can be judged to have a unique class for the parent element), and if so, the first-level click event.
Give me a chestnut:
Html:
<DivID= "ClickMe">Click Me</Div><DivID= "BG"class= "BG"> <DivID= "inner"> <H2>Content Area</H2> <DivID= "BTN">Click Me</Div> </Div></Div>
Css:
body { width:100%; Position:absolute; left:0; top:0; bottom:0} #bg { width:100%; Position:absolute; left:0; top:0; bottom:0; Background:rgba (0, 0, 0,. 5); Display:none;} #bg. Show { display:block;} #inner { width:200px; height:200px; Background: #fff;}
Js:
var function (elem) { return document.getElementById (elem)}$ (function() { $ ( ' BG '). Classlist.add (' show ')}$ (function(e) { if( E.target.classlist.contains (' bg ')) { this. Classlist.remove (' Show') }}$ ( function() { $ (' BG '). Classlist.remove (' Show ')}
Execution: https://jsfiddle.net/9u4y1sru/
Jquery:
Html:
<Pclass= "BTN">Click Me</P><Divclass= "BG"> <ahref= "javascript:;"class= "BTN2">Click Me2</a></Div>
Css:
. BG{position:fixed;width:100%;Height:100%;background:Rgba (0,0,0,0.3);Display:None;Top:0; Left:0;}. BG. btn2{Display:Block;width:200px;Height:200px;background:#fff;margin:100px;padding:200px;}
Js:
$ ('. btn '). Click (function(e) { $ ('. BG '). Show (); }); $ ('. BG '). Click (function(e) { if($ (e.target). Hasclass (' BG ')) { $ ( '. BG '). Hide (); } ); $ ('. btn2 '). Click (function() { alert (' I'm still in '); });
Blocking bubbling Event resolution 2