Example of JavaScript Implementation Event Interrupt Propagation and Behavior Blocking Methods
- 2021-07-12 05:10:50
- OfStack
Event propagation
MicroSoft is designed so that when an event is fired on an element, it will then be fired on the parent node of the node, and so on, with Event 1 propagating straight up the DOM tree until it reaches the top-level object document element. This bottom-up way of event propagation is called "event bubbling", that is, event propagation.
How to interrupt the propagation of events?
stopPropagation()
w3c Cancel Bubble
cancleBubble = true
IE Cancel Bubble
Cancel the default effect of events:
returnValue = false
IE Cancel Event Effect
defaultPrevent()
w3c Cancel Event Effect
<div id='aa'>
<div id='bb'>
<div id ='cc'></div>
</div>
</div>
#aa{
width: 600px;
height: 600px;
background: gray;
}
#bb{
width: 400px;
height: 400px;
background: green;
}
#cc{
width: 200px;
height: 200px;
background: red;
}
Capture writing stops propagating from the top down
document.getElementById('aa').addEventListener('click',function (ev){alert('aa');ev.stopPropagation();},true);// The result is captured aa Plus true From bubbling to catching From top to bottom
document.getElementById('bb').addEventListener('click',function (){alert('bb')},true);
document.getElementById('cc').addEventListener('click',function (){alert('cc')},true);
Bubble writing stops spreading from bottom to top
document.getElementById('aa').addEventListener('click',function (){alert('aa');});// Plus true From bubbling to catching From top to bottom
document.getElementById('bb').addEventListener('click',function (){alert('bb')});
document.getElementById('cc').addEventListener('click',
function (ev){
alert('cc');
ev.stopPropagation();
// ev.cancleBubble = true;//IE Under Cancel bubbling method
}); // The result is that it comes out cc Stop propagation
}
Cancel event effect
returnValue = false
//IE Cancel Event Effect
preventDefault()
//w3c Cancel Event Effect
document.getElementsByTagName('a')[0].onclick = function (ev){
alert(' Click ');
// Achieve the effect of ending the event But the function still runs down
//
ev.preventDefault();
alert(' Has been intercepted ');
}
Summarize
The above is the whole content of this article. I hope the content of this article can bring 1 certain help to everyone's study or work. If you have any questions, you can leave a message for communication.