HTML DOM-->事件对象(阻止冒泡、阻止默认行为)

1.阻止冒泡:

   stopPropagation()

  举例:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>js_excise</title>    
    </head>

    <body>
        <div id="box1" style="background-color: #00FFFF;width: 70px;height: 70px;">
        </div>
        <input type="text" id="box2">
        <script type="text/javascript">
            document.body.onclick=function(){
                this.style.backgroundColor='yellow'
            }
            
            document.getElementById('box1').onclick= function(e){
                var ev = e || window.event
                //阻止冒泡
                ev.stopPropagation()
                this.style.backgroundColor = 'pink'
            }
            
            document.getElementById('box2').onclick = function(e){
                var ev = e || window.event
                //阻止冒泡
                ev.stopPropagation()
            }

        </script>
    </body>
</html>

  输出:body元素背景不会变成黄色

2.阻止默认行为:

  preventDefault() 方法阻止元素发生默认的行为。

  例如:

    当点击提交按钮时阻止对表单的提交

    阻止以下 URL 的链接

  代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>js_excise</title>    
    </head>

    <body>
        <a id='box1' href="https://www.cnblogs.com/">学习一下</a>
        <script type="text/javascript">
            document.getElementById('box1').onclick= function(e){
                var ev = e || window.event
                var info = window.confirm('您浏览的浏览器存在风险,是否继续浏览?')
                if (info == false){
                    //阻止默认行为
                    ev.preventDefault()
                }    
            }
        </script>
    </body>
</html>

  输出:若点击对话框“取消”,将不会跳入链接页面

posted @ 2020-05-04 22:41  abner_pan  阅读(898)  评论(0编辑  收藏  举报