阻止冒泡的方法 event.stopPropagation();

    xiaoxiao2026-09-10  3

    标准浏览器 和  ie浏览器    w3c的方法是event.stopPropagation()         IE则是使用event.cancelBubble = true       bubble   冒泡  泡泡       cancel 取消   兼容的写法:   if(event && event.stopPropagation)         {              event.stopPropagation();  //  w3c 标准         }           else           {

                  event.cancelBubble = true;  // ie 678  ie浏览器8  

    }

    例子一

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <button id="btn">按钮</button> </body> <script> var btn=document.getElementsByTagName("button")[0]; document.οnclick=function(){ alert("点击空白"); } btn.οnclick=function(event){ alert("点击button"); //阻止冒泡 event.stopPropagation(); } window.οnclick=function(){ alert("点击window"); } </script> </html> 例子二 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> *{ margin: 0px; padding: 0px; border: 0px; } #bg{ width: 100%; height:100%; opacity: 0.5; background-color: #333; position: fixed; top:0; display: none; } #show{ width: 300px; height: 300px; background-color: white; position: relative; top:20%; left: 40%; display: none; } </style> </head> <body> <a href="#">登录</a> <a href="#">注册</a> <div id="bg"></div> <div id="show"></div> </body> <script> var mya=document.getElementsByTagName("a")[0]; var bg=document.getElementById("bg"); var show=document.getElementById("show"); mya.onclick = function(event){ bg.style.display="block"; show.style.display="block"; event.stopPropagation(); } document.οnclick=function(event){ var target=event.target.id; alert(target); if(target!="show"){ bg.style.display="none"; show.style.display="none"; } } </script> </html>

     }

    转载请注明原文地址: https://ju.6miu.com/read-1311943.html
    最新回复(0)