Html事件冒泡

原以为span不同于input,事件冒泡会被父级标签吞噬,写了个测试事件冒泡的Demo,发现并不是想得那样。另外:event.stopPropagation()以及event.stopImmediatePropagation()并不能阻止span冒泡到a标签中,而简单粗暴的return false却可以。

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <title>Bubbling</title>
 5     <style type="text/css">
 6         * {
 7             font-size:30px;
 8         }
 9         div {
10             border: 1px blue solid;
11         }
12         span {
13             border: 1px blue solid;
14         }
15     </style>
16     <script type="text/javascript">
17         function setforeColor(sender) {
18             sender.style.color = "red";
19         }
20 
21         function setbgColor(sender) {
22             sender.style.background = "green";
23             return false;
24         }
25     </script>
26 </head>
27 <body>
28     <div>
29         <span onclick="setforeColor(this)">span tag</span> in div
30     </div>
31     <br>
32     <div>
33         <input type="button" value="Button" onclick="setforeColor(this)"/> in div
34     </div>
35     <br>
36     <a href="https://www.baidu.com" style="text-decoration:none;display:block;">
37         <span onclick="setforeColor(this);return false">span tag</span> in anchor
38     </a>
39     <br>
40     <a href="https://www.baidu.com" style="text-decoration:none;display:block;">
41         <span onclick="setbgColor(this)">span tag</span> in anchor
42     </a>
43 </body>
44 </html>

更多参考:https://en.wikipedia.org/wiki/Event_bubblinghttp://javascript.info/bubbling-and-capturing

posted @ 2017-10-11 23:46  天琊蓝  阅读(803)  评论(1编辑  收藏  举报