PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

Javascript如何阻止事件冒泡和事件本身发生

autoload
autoload 原创
2021-04-09 11:27:18 1822浏览

    在javascript事件冒泡是由节点产生,然后会影响到父节点,逐级上升,最后慢慢影响到整个页面,但是有时我们想要阻止事件冒泡的发生甚至事件本身的发生呢?本文就带大家一起来了解一下。

1.阻止事件冒泡发生

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .boxA {
            overflow: hidden;
            width: 300px;
            height: 300px;
            margin: 100px auto;
            background-color: blue;
            text-align: center;
        }       
        .boxB {
            width: 200px;
            height: 200px;
            margin: 50px;
            background-color: green;
            line-height: 200px;
            color: #fff;
        }
    </style>
</head>

<body>
    <div class="boxA">
        <div class="boxB">boxB</div>
    </div>
    <script>
        var boxA = document.querySelector(&#39;.boxA&#39;);
        var boxB = document.querySelector(&#39;.boxB&#39;);
        boxA.onclick = function (e) {
        console.log(&#39;我被点击了boxA&#39;);
    };
    boxB.onclick = function (e) {
        e.cancelBubble=true; //不冒泡
        console.log(&#39;我被点击了boxB&#39;);
    };
    </script>
</body>
</html>

2.阻止事件本身发生

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<form action="http://www.php.cn" method="POST">
<button type="submit">按钮1</button>
</form>    
<body>
    <script>
        const btn=document.querySelector("button");
        console.log(btn);
        btn.addEventListener("click",function(e){
            e.preventDefault();
        });
    </script>
</body>
</html>

推荐:《2021年js面试题及答案(大汇总)

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