事件捕获、冒泡、委托
1)事件捕获:由外向内触发事件(记:捕获是由表层伸入水的深处)
2)事件冒泡:由内向外触发事件(记:冒泡由水深处到表层)
3)事件先捕获再冒泡:这是目前主流浏览器采用的做法,试验代码如下
先了解事件绑定函数:addEventListener(event, listener, useCapture)
event: 什么事件
listener: 监听的响应函数
useCapture: true表示使用捕获机制,false表示使用冒泡机制。(默认为false)
<html lang="zh-cn">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>js事件机制</title>
<style>
#parent{
width: 200px;
height:200px;
text-align: center;
line-height: 3;
background: green;
}
#child{
width: 100px;
height: 100px;
margin: 0 auto;
background: orange;
}
</style>
</head>
<body>
<div id="parent">
父元素
<div id="child">
子元素
</div>
</div>
<script type="text/javascript">
var parent = document.getElementById("parent");
var child = document.getElementById("child");
document.body.addEventListener("click",function(e){
console.log("click-body");
},false);
parent.addEventListener("click",function(e){
console.log("click-parent");
},false);
child.addEventListener("click",function(e){
console.log("click-child");
},false);
// 捕获事件
document.body.addEventListener("click",function(e){
console.log("click-body 捕获");
},true);
parent.addEventListener("click",function(e){
console.log("click-parent 捕获");
},true);
child.addEventListener("click",function(e){
console.log("click-child 捕获");
},true);
</script>
</body>
</html>
打印结果:
分析:
4)事件委托
事件委托用一句话描述:利用冒泡机制,通过委托父元素给子元素注册事件
好处:减少绑定次数;后期添加的子元素相当于自动注册了事件;
例子:通过parent的元素给child1和child2元素注册事件
<body>
<div id="parent">
父
<div id="child1">
孩子1
</div>
<div id="child2">
孩子2
</div>
</div>
<script type="text/javascript">
var parent = document.getElementById("parent");
parent.addEventListener('click',function(e){
if(e.target.id == 'child1'){
console.log('click child1');
}else if(e.target.id == 'child2'){
console.log('click child2');
}
},false)
</script>
</body>