刀刀网
您的当前位置:首页如何实现Html事件冒泡

如何实现Html事件冒泡

来源:刀刀网


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


<!DOCTYPE html>
<html>
<head>
 <title>Bubbling</title>
 <style type="text/css">
 * {
 font-size:30px;
 }
 div {
 border: 1px blue solid;
 }
 span {
 border: 1px blue solid;
 }
 </style>
 <script type="text/javascript">
 function setforeColor(sender) {
 sender.style.color = "red";
 }

 function setbgColor(sender) {
 sender.style.background = "green";
 return false;
 }
 </script>
</head>
<body>
 <div>
 <span onclick="setforeColor(this)">span tag</span> in div
 </div>
 <br>
 <div>
 <input type="button" value="Button" onclick="setforeColor(this)"/> in div
 </div>
 <br>
 <a href="https://www.baidu.com" style="text-decoration:none;display:block;">
 <span onclick="setforeColor(this);return false">span tag</span> in anchor
 </a>
 <br>
 <a href="https://www.baidu.com" style="text-decoration:none;display:block;">
 <span onclick="setbgColor(this)">span tag</span> in anchor
 </a>
</body>
</html>
显示全文