【发布时间】:2018-11-13 21:46:26
【问题描述】:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>capture and bubble</title>
<style type="text/css">
#child{
background: red;
width:50px;
height:50px;
}
#father{
width:100px;
height:100px;
background:green;
}
</style>
</head>
<body>
<div id='father'>
<div id='child'></div>
</div>
</body>
<script type="text/javascript">
var parent = document.getElementById("father");
var child = document.getElementById('child');
var html = document.getElementsByTagName("html")[0];
var body = document.body;
parent.addEventListener("click",function() {
console.log("I am capturing parent");
},true);
parent.addEventListener("click",function() {
console.log("I am parent");
},false);
child.addEventListener("click",function() {
console.log("I am capturing child");
},true);
child.addEventListener("click",function() {
console.log("I am child");
},false);
body.addEventListener("click",function() {
console.log("I am capturing body");
},true);
body.addEventListener("click",function() {
console.log("I am body");
},false);
html.addEventListener("click",function() {
console.log("I am capturing html");
},true);
html.addEventListener("click",function() {
console.log("I am html");
},false);
parent.addEventListener("click",function() {
console.log("I am capturing parent");
},true);
parent.addEventListener("click",function() {
console.log("I am parent");
},false);
</script>
</html>
对于上面包含一个显示捕获和冒泡执行顺序的js的html,我为父级(div父亲)绑定了两次捕获和气泡的两个监听器,为父级(div父亲)绑定了一对捕获和气泡) 是从 js 脚本部分的第 5 行到第 10 行;父级(div 父级)的另一对捕获和气泡位于 js 脚本部分的末尾。
点击绿色的div(父div),在控制台中获取结果。
test.html:50 I am capturing html
test.html:44 I am capturing body
test.html:32 I am capturing parent
test.html:35 I am parent
test.html:56 I am capturing parent
test.html:59 I am parent
test.html:47 I am body
test.html:53 I am html
为什么结果不是如下?
test.html:50 I am capturing html
test.html:44 I am capturing body
test.html:32 I am capturing parent
test.html:56 I am capturing parent
test.html:35 I am parent
test.html:59 I am parent
test.html:47 I am body
test.html:53 I am html
请详细说明。
【问题讨论】:
标签: javascript html events capture