zoukankan      html  css  js  c++  java
  • JQuery阻止事件冒泡

    我们在平时的开发过程中,肯定会遇到在一个div(这个div可以是元素)包裹一个div的情况,但是呢,在这两个div上都添加了事件,如果点击里面的div我们希望处理这个div的事件,但是呢,我们不希望外层的div的事件也执行,这时候我们就要用到阻止冒泡

    通俗点来说吧,你在家里看电视,躲在自己的小房间,但是你不希望声音传到隔壁父母的耳朵里,这时候,你可能躲在被窝里,或者墙壁的隔音效果很好,阻隔声音可以理解为阻止冒泡。

    阻止事件冒泡的三种手段

    1、return false:可以阻止默认事件和冒泡事件

    2、event.stopPropagation/IE下event.cancelBubble  = true;:可以阻止冒泡事件但是允许默认事件

    3、event.preventDefault();/IE下event.returnValue = false:可以阻止默认事件但是允许冒泡事件

    上面的三种方法运用在不同的场景,可以合理运用,下面是代码,可以自己做一些测试:

    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title>jQuery阻止冒泡</title>
        <style>
            .div1{
                width: 140px;
                border: 1px solid blue;
            }
            .div2{
                width: 100px;
                height: 100px;
                margin: 20px;
                border: 1px solid red;
            }
        </style>
    </head>
    <body>
    <div class="div1">
        <div class="div2">
            点我呀!!!!
        </div>
    </div>
    
    <a href="http:www.baidu.com" id="a1">百度</a>
    
    <script src="../js/jquery/jquery.min.js"></script>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
    <script>
        $('.div1').bind('click',function(){
            alert("div1");
        });
        $('.div2').bind('click',function(){
            alert("div2");
    //        return false;//也可以通过return false 阻止冒泡
            if(window.event){//IE下阻止冒泡
                event.cancelBubble  = true;
            }else{
                event.stopPropagation();
            }
        });
        $('#a1').bind('click',function(){
            if(window.event){//IE下阻止默认事件
                event.returnValue = false;
            }else{
                event.preventDefault();
            }
            alert("我是链接");
            //return false;//如果不添加任何阻止事件,先弹框,后跳转,我们可以通过return false阻止跳转
        });
    
    </script>
    </body>
    </html>
  • 相关阅读:
    UnityEngine中Animator相关类的说明
    MecanimControl插件随笔
    Mecanim Control
    Unity3D
    Unity Mecanim在大型mmo中的应用
    Unity3D 性能优化
    Unity3D 图形优化
    U3D开发性能优化笔记(待增加版本.x)
    通过JS语句判断WEB网站的访问端是电脑还是手机
    jquery 鼠标事件汇总
  • 原文地址:https://www.cnblogs.com/cangowu/p/5115090.html
Copyright © 2011-2022 走看看