The effect I want to achieve is to click the button to show and hide the Div, click on document to hide the div. However, if there is no cancel event bubbling, the click button will never show Div, because the event layer to bubble up, and finally go to document, directly executed the Click event on the document. In fact, it is not not show Div, but show the instant and executed the document click event and hidden, because the speed is too fast to see, it may be possible to add alert in the middle (' a ');
<!DOCTYPE HTML><HTML><Head><MetaCharSet= "Utf-8"><title></title><style>#div1{width:300px;Height:300px;background:#000;Display:None;}</style></Head><Body><inputID= "BTN1"type= "button"value= "Display" /><DivID= "Div1"></Div><Scripttype= "Text/javascript"> varobtn=document.getElementById ('BTN1'); varOdiv=document.getElementById ('Div1'); Obtn.onclick= function(EV) {varoevent=EV||event; if(ODiv.style.display== 'None') {ODiv.style.display= 'Block'; } Else{ODiv.style.display= 'None'; } oevent.cancelbubble= true;//Cancel Event Bubbling} Document.onclick= function() {ODiv.style.display= 'None'; }</Script></Body></HTML>
Cancel Event Bubbling