首页 > 代码库 > JS阻止事件传播和默认行为

JS阻止事件传播和默认行为

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> 3 <head> 4     <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> 5     <title>Document</title> 6     <style> 7         body{ 8             margin: 200px; 9         }10         div{11             width: 200px;12             height: 200px;13             background: #ccc;14         }15     </style>16 </head>17 <body>18     <div>19         <span>go</span>20         21     </div>22     <a href="http://baidu.com" target="blank">baidu</a>23     <script>24         var oDiv = document.getElementsByTagName("div")[0],25             oSpan = document.getElementsByTagName("span")[0],26             aTag = document.getElementsByTagName("a")[0];27         oDiv.onclick = function(){28             alert("div");29         }30         oSpan.onclick = function(evt){31             alert("span");32             stopBubble(evt);33         }34 35         aTag.onclick = function(evt){36             alert("a link");37             stopBubble(evt);38         }39         //阻止事件的传播和默认行为40         function stopBubble(evt){41             var evt = evt || event;42             if(evt.stopPropagation){43                 //IE上阻止事件的传播44                 evt.stopPropagation();45                 //阻止默认行为46                 // evt.preventDefault();47             }else{48                 //w3c标准的阻止事件的传播49                 evt.cancelBubble = true;50                 //w3c标准的阻止默认行为51                 evt.returnValue = http://www.mamicode.com/false;52             }53         }54     </script>55 </body>56 </html>

 

JS阻止事件传播和默认行为