事件捕获_事件冒泡
原创
©著作权归作者所有:来自51CTO博客作者diligenceday的原创作品,请联系作者获取转载授权,否则将追究法律责任
件冒泡和事件捕获的demo了
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
.p{
width:500px;
height:500px;
background:#CCF;
}
.s{
width:300px;
height:300px;
background:#fff;
}
.min{
width:100px;
height:100px;
background:#063;
}
</style>
</head>
<body>
<div class="p">
<div class="s">
<div class="min"></div>
</div>
</div>
<script>
window.alert = function (msg) {
console.log(msg);
};
var p = document.getElementsByClassName('p')[0];
var s = document.getElementsByClassName('s')[0];
p.addEventListener('click', function (e) {
alert( (e.target === e.currentTarget) + ' '+ e.eventPhase)
alert('父节点捕获11');
}, true);
p.addEventListener('click', function (e) {
alert( (e.target === e.currentTarget) + ' '+ e.eventPhase)
alert('父节点冒泡')
}, false);
s.addEventListener('click', function (e) {
alert( (e.target === e.currentTarget) + ' '+ e.eventPhase)
alert('子节点捕获11');
}, true);
s.addEventListener('click', function (e) {
alert( (e.target === e.currentTarget) + ' '+ e.eventPhase)
alert('子节点冒泡')
}, false);
/*e.target时指向当前目标,e.currentTarget是指向点击的this*/
</script>
</body>
</html>
事件的eventPhase说明了事件执行所在状态, 1为捕获, 2为在目标上, 3为冒泡阶段, 如果;
Event.CAPTURING_PHASE
| 1
|
Event.AT_TARGET
| 2
|
Event.BUBBLING_PHASE
| 3
|
当我们点击的是目标元素的时候, 捕获的事件, 冒泡的事件和 正常绑定的事件都会触发, 而且eventPhase的值为2,
当我们点击的是目标元素内部元素时候,事件会根据捕获,标准, 冒泡的顺序执行 , 捕获时eventPhase的值为1, 冒泡和标准时候eventPhase值为3;
某些事件只捕获, 没有冒泡, 比如img的onload事件, 有些事件即冒泡又捕获,比如click事件。 虽然说捕获平常用不到, 但是也有存在的意义吧;
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body style="padding:100px">
<div id="div0">div0</div>
<div>
body
</div>
<script>
var l = function() {
console.log( arguments[0] )
};
var div0 = document.getElementById("div0");
div0.addEventListener("click", function(ev) {
l(ev.eventPhase);
l("div0点击事件");
});
document.body.addEventListener("click", function(ev) {
l(ev.eventPhase);
l("在目标上");
});
document.body.onclick = function(ev) {
l(ev.eventPhase);
l("在目标上");
}
document.body.addEventListener("click", function(ev) {
l(ev.eventPhase);
l("冒泡");
}, false);
document.body.addEventListener("click", function(ev) {
l(ev.eventPhase);
l("捕获");
}, true);
</script>
</body>
</html>
天道酬勤