事件捕获和事件冒泡

addEventListener和removeEventListener

// type:事件类型,不含"on",比如"click"、"mouseover"、"keydown";
// 而attachEvent的事件名称,含含"on",比如"onclick"、"onmouseover"、"onkeydown";
// listener:事件处理函数
// useCapture是事件冒泡,还是事件捕获,默认false,代表事件冒泡类型,true表示事件捕获
addEventListener(type, listener, useCapture);

测试代码:

<script>
    window.onload = function(){
        var outA = document.getElementById("outA");  
        var outB = document.getElementById("outB");  
        var outC = document.getElementById("outC");  
        var outD = document.getElementById("outD");  
        
        // 使用事件冒泡
        outA.addEventListener('click',function(){alert(1);},false);
        outB.addEventListener('click',function(){alert(2);},false);
        outC.addEventListener('click',function(){alert(3);},false);
        outD.addEventListener('click',function(){alert(4);},false);
    };
</script>
<body>
    <div id="outA" style="width:400px; height:400px; background:#CDC9C9;position:relative;">
        <div id="outB" style="height:200; background:#0000ff;top:100px;position:relative;">
            <div id="outC" style="height:100px; background:#FFB90F;top:50px;position:relative;">
                <div id="outD" style="height:80px; background:#8f8f8f;top:30px;position:relative;"></div>
            </div> 
        </div>
    </div>
</body>

点击D区域

  1. 当是事件捕获时(useCapture=true):


    事件捕获.gif
  2. 当是事件冒泡时(useCapture=false):


    事件冒泡.gif
  3. 当AC为true,BD为false时:


    混合.gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容