首頁  >  文章  >  web前端  >  Javascript如何阻止事件冒泡和事件本身發生

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

autoload
autoload原創
2021-04-09 11:27:181965瀏覽

    在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面試題目及答案(大總結)

以上是Javascript如何阻止事件冒泡和事件本身發生的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn