addEventListener和removeEventListener
// type:事件類型,不含"on",比如"click"霉旗、"mouseover"攒发、"keydown";
// 而attachEvent的事件名稱,含含"on",比如"onclick"、"onmouseover"呈驶、"onkeydown";
// listener:事件處理函數(shù)
// 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區(qū)域
-
當是事件捕獲時(useCapture=true):
事件捕獲.gif -
當是事件冒泡時(useCapture=false):
事件冒泡.gif -
當AC為true,BD為false時:
混合.gif