事件捕获和事件冒泡
2016-08-04 本文已影响171人
在路上_W
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区域
-
当是事件捕获时(useCapture=true):
事件捕获.gif -
当是事件冒泡时(useCapture=false):
事件冒泡.gif -
当AC为true,BD为false时:
混合.gif