如何实现Html事件冒泡

一个新手
一个新手 原创
2017-10-12 10:33:17 1361浏览

原以为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>

以上就是如何实现Html事件冒泡的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。