下面小编就为大家带来一篇js 事件的传播机制(实例讲解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
事件的默认传播机制:
捕获阶段:从外向里依次查找元素
目标阶段:从当前事件源本身的操作
冒泡阶段:从内到外依次触发相关的行为(我们最常用的就是冒泡阶段)
具体见下图:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#outer{
margin:20px auto;
padding:20px;
width:300px;
height:300px;
background:#008000;
}
#inner{
padding:20px;
width:200px;
height:200px;
background:blue;
}
#center{
padding:20px;
width:100px;
height:100px;
background:yellow;
}
</style>
</head>
<body>
<div id='outer'>
<div id='inner'>
<div id='center'></div>
</div>
</div>
<script>
var outer = document.getElementById('outer'),inner = document.getElementById('inner'),center = document.getElementById('center');
//使用DOM0级事件绑定给元素的某一个行为绑定的方法,都是在行为触发后的冒泡阶段把方法执行的
document.body.onclick = function(){
console.log('body')
}
outer.onclick = function(){
console.log('outer')
}
inner.onclick = function(){
console.log('inner')
}
center.onclick = function(){
console.log('center')
}
//addEventListener 第一个参数是行为的类型 第二个参数是给当前的行为定义的方法 第三个参数是控制在哪个阶段发生:true 在捕获阶段发生 false在冒泡阶段发生
document.body.addEventListener('click',function(){
console.log('body')
},false)
outer.addEventListener('click',function(){
console.log('outer')
},true)
inner.addEventListener('click',function(){
console.log('inner')
},false)
//输出 outer inner body
</script>
</body>
</html>
以上这篇js 事件的传播机制(实例讲解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。 |