• canselBubble 和 stopPropagation理解


    // cancelBubble在IE下有效
     // stopPropagation在Firefox下有效

     
    stopPropagation 

    不再派发事件。

    终止事件在传播过程的捕获、目标处理或起泡阶段进一步传播。调用该方法后,该节点上处理该事件的处理程序将被调用,事件不再被分派到其他节点。

    cancelable 事件返回一个布尔值。如果用 preventDefault() 方法可以取消与事件关联的默认动作,则为 true,否则为 fasle。

    一个小例子
    <!DOCTYPE html>
    <head>
        <title> 阻止JavaScript事件冒泡传递(cancelBubble 、stopPropagation)</title>
        <meta name="keywords" content="JavaScript,事件冒泡,cancelBubble,stopPropagation" />
        <script type="text/javascript">

            // cancelBubble在IE下有效
            // stopPropagation在Firefox下有效
            function doSomething (obj,evt) {
                alert(obj.id);
                var e=(evt)?evt:window.event;
                if (window.event) {
                    e.cancelBubble=true;
                } else {
    //e.preventDefault();
                    e.stopPropagation();
                }
            }
        </script>
    </head>
    <body>
    <div id="parent1" onclick="alert(this.id)" style="margin-bottom 20px;250px;background-color:yellow">
        <p>This is parent1 div.</p>
        <div id="child1" onclick="alert(this.id)" style="margin-bottom 20px;200px;background-color:orange">
            <p>This is child1.</p>
        </div>
        <p>This is parent1 div.</p>
    </div>
    <br />
    <div id="parent2" onclick="alert(this.id)" style="margin-bottom 20px;250px;background-color:cyan;">
        <p>This is parent2 div.</p>
        <div id="child2" onclick="doSomething(this,event);" style="margin-bottom 20px;200px;background-color:lightblue;">
            <p>This is child2. Will bubble.</p>
        </div>
        <p>This is parent2 div.</p>
    </div>
    </body>
    </html>
     
  • 相关阅读:
    分析ASP.NET读取XML文件4种方法
    WordPress 主题教程 #4a:Header 模板
    WordPress 主题教程 #4b:Header 模板 2
    倍受好评的美国主机JustHost使用全攻略教程
    单链表的创建、插入、删除、倒置操作
    WordPress 主题教程:从零开始制作 WordPress 主题
    google adsense 设置建议
    PHP:10个不常见却非常有用的PHP函数
    WordPress 主题教程 #2:模板文件和模板
    必须掌握的八个cmd命令行
  • 原文地址:https://www.cnblogs.com/xiaohong/p/3636202.html
Copyright © 2020-2023  润新知