Javascript怎样阻止事件冒泡和事件本身发生

2023-06-26,

本篇内容介绍了“Javascript怎样阻止事件冒泡和事件本身发生”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

JavaScript可以做什么

1.可以使网页具有交互性,例如响应用户点击,给用户提供更好的体验。
2.可以处理表单,检验用户的输入,并提供及时反馈节省用户时间。
3.可以根据用户的操作,动态的创建页面。
4使用JavaScript可以通过设置cookie存储在浏览器上的一些临时信息。

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('.boxA');
        var boxB = document.querySelector('.boxB');
        boxA.onclick = function (e) {
        console.log('我被点击了boxA');
    };
    boxB.onclick = function (e) {
        e.cancelBubble=true; //不冒泡
        console.log('我被点击了boxB');
    };
    </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>

“Javascript怎样阻止事件冒泡和事件本身发生”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注本站网站,小编将为大家输出更多高质量的实用文章!

《Javascript怎样阻止事件冒泡和事件本身发生.doc》

下载本文的Word格式文档,以方便收藏与打印。