• 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; 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>

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

  • 相关阅读:
    【转】Intellij IDEA常用配置详解
    scala(一)
    scala(三)
    Scrapy学习篇(六)之Selector选择器
    Scrapy学习篇(五)之Spiders
    Scrapy学习篇(四)之数据存储
    Scrapy学习篇(三)之创建项目
    Scrapy学习篇(二)之常用命令行工具
    Scrapy学习篇(一)之框架
    git实现github仓库和本地仓库同步
  • 原文地址:https://www.cnblogs.com/abner-pan/p/12828631.html
Copyright © 2020-2023  润新知