事件冒泡
当一个元素接受到事件的时候,会把它接收到的所有事件传播给它的父级,一直到顶层window,叫事件冒泡机制;
例子:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>事件冒泡</title> <style> div{padding:40px;} #div1{ background: red; } #div2{ background:green; } #div3{background: blue;} </style> <script> window.onload=function(){ var oDiv1=document.getElementById(‘div1‘); var oDiv2=document.getElementById(‘div2‘); var oDiv3=document.getElementById(‘div3‘); function fn1(){ alert(this.id); } //事件函数绑定 oDiv1.onclick=fn1;//告诉div1,如果它接收到了一个点击事件,那它就去执行fn1 oDiv2.onclick=fn1; oDiv3.onclick=fn1;//div3,div1 事件冒泡 } </script> </head> <body> <div id="div1"> <div id="div2"> <div id="div3"></div> </div> </div> </body> </html>
<iframe style="width: 100%; height: 300px" src=" https://jsfiddle.net/v2yjremt/embedded/result,js,html,css/"> </iframe>
阻止冒泡:在当前要阻止冒泡的事件函数中调用event.cancelBubble=true;
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>阻止冒泡</title> <style> #div1{ width:100px; height:200px; border:1px solid red; display: none; } </style> <script> window.onload=function(){ var oBtn=document.getElementById(‘btn1‘); var oDiv=document.getElementById(‘div1‘); oBtn.onclick=function(ev){ var oEvent=ev||event; //阻止当前事件函数事件冒泡 oEvent.cancelBubble=true; oDiv.style.display=‘block‘; } document.onclick=function(){ /* setTimeout(function(){//观察事件冒泡:div出现一秒钟后隐藏了 oDiv.style.display=‘none‘; },1000);*/ oDiv.style.display=‘none‘; } } </script> </head> <body> <input type="button" value="按钮" id="btn1"> <div id="div1">点击按钮div就出现,点击除按钮以外的部分div就消失</div> </body> </html>
<iframe style="width: 100%; height: 300px" src=" https://jsfiddle.net/7f5qgLm3/embedded/result,js,html,css/"> </iframe>
对比没有取消冒泡事件时的效果,下面用了延时器一遍观察效果
<iframe style="width: 100%; height: 300px" src=" https://jsfiddle.net/7f5qgLm3/1/embedded/result,js,html,css/"> </iframe>
事件冒泡的运用
下面是一个网站中常见的功能——分享到
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>事件冒泡</title> <style> #div1{ width:100px; height:200px; background: red; position: absolute; left:-100px; top:100px; } #div2{ width:30px; height:60px; position: absolute; right:-30px; top:70px; background:#000000; color:#ffffff; text-align: center; } </style> <script> window.onload=function(){ var oDiv=document.getElementById(‘div1‘); oDiv.onmouseover=function(){ this.style.left=0+‘px‘;//鼠标移动到div2时,div2接收到over、out事件时它自己不做,传播给父级div1执行 } oDiv.onmouseout=function(){ this.style.left=-100+‘px‘; } } </script> </head> <body> <div id="div1"> <div id="div2">分享到</div> </div> </body> </html>
效果:
<iframe style="width: 100%; height: 300px" src=" https://jsfiddle.net/aLurk1p1/embedded/result,js,html,css/"> </iframe>
时间: 2024-10-11 01:20:07