zoukankan      html  css  js  c++  java
  • js时间冒泡,阻止事件冒泡

    首先解释一下事件冒泡神什么,

    在js中,假如在div中嵌套一个div

    <style type="text/css">
        #box1{width:500px;height:500px;background:#900;}
         #box2{width:400px;height:400px;background:#090;}
          #box3{width:300px;height:300px;background:#009;}
           #box4{width:200px;height:200px;background:#990;}
            #box5{width:100px;height:100px;background:#099;}
    </style>
    
    <body>
    <div id="box1">
        <div id="box2">
           <div id="box3">
                    <div id="box4">
                           <div id="box5">
                           </div>
                    </div>
           </div>
        </div>
    </div>
        
    </body>

    当你用onclick事件时,当你点击id=‘box4’的div,事件会一直传递到box3,box2,box1,html

    这就叫事件的冒泡,有时候不需要冒泡,所以会阻止冒泡。

    <script>
        window.onload =function()
        {
            var $=function(_id){return document.getElementById(_id);}
            document.onclick=function()
            {
                alert("点击的document");
            }
            document.body.onclick=function()
            {
                 alert("点击的body");
            }
            $("box1").onclick=function()
            {
                alert("你点击的id为:"+this.id +"的div");
            }
             $("box2").onclick=function()
            {
                alert("你点击的id为:"+this.id +"的div");
            }
             $("box3").onclick=function(e)
            {
                e=window.event || e;  //IE支持的是windows事件,而标准e事件是chromo额firefox支持
                e.stopPropagation();  //阻止冒泡的方法,而ie不支持這个方法,但支持cancelBubble属性
                alert("你点击的id为:"+this.id +"的div");
            }
             $("box4").onclick=function(e)
            {
                //全浏览器兼容的阻止冒泡
                e=e ||window.event ;
                e.stopPropagation?(stopPropagation()):(e.cancelBubble=true);
                alert("你点击的id为:"+this.id +"的div");
              
            }
             $("box5").onclick=function()
            {
                alert("你点击的id为:"+this.id +"的div");
            }
        }   
     </script>

    firefox,chrome中用的是

    stopPropagation()函数来阻止冒泡

    ie用的是cancelBubble=ture;這个属性来阻止冒泡

  • 相关阅读:
    程序编译的四个阶段
    c++的符号表的肤浅认识
    git高级用法之cheery-pick
    rust 使用国内镜像,快速安装方法
    protobuf 的enum与string转换
    c++ 获取GMT 时间和字符串
    proto3 不支持内建类型的非空判断即 hasXXX
    cmake 中的 compile_commands.json 文件
    整数划分问题(记忆化搜索和DP方法)
    查找系列合集-二分查找
  • 原文地址:https://www.cnblogs.com/biyongyao/p/5840549.html
Copyright © 2011-2022 走看看