事件处理机制的三个阶段(捕获阶段,目标阶段,冒泡阶段)
冒泡阶段:事件从内向外执行捕获阶段:事件从外向内执行;
- addEventListener(type,fn,useCapture)
- useCapture:事件处理机制(捕获阶段true,目标阶段,冒泡阶段false)默认为冒泡阶段
- 捕获阶段:事件从外向内执行; 冒泡阶段:事件从内向外执行
捕获情况:
<style>
#parent{
height: 300px;
width: 300px;
background-color: red;
}
#son{
height: 100px;
width: 100px;
background-color: green;
}
</style>
</head>
<body>
<div id="parent">
<div id="son"></div>
</div>
</body>
<script>
document.getElementById('parent').addEventListener('click',function(e){
console.log('是你爸爸')
},true)
document.getElementById('son').addEventListener('click',function(e){
console.log('你儿子')
},true)
</script>
冒泡情况:
<style>
#parent{
height: 300px;
width: 300px;
background-color: red;
}
#son{
height: 100px;
width: 100px;
background-color: green;
}
</style>
</head>
<body>
<div id="parent">
<div id="son"></div>
</div>
</body>
<script>
document.getElementById('parent').addEventListener('click',function(e){
console.log('是你爸爸')
},false)
document.getElementById('son').addEventListener('click',function(e){
console.log('你儿子')
},false)
</script>
阻止冒泡行为:
<style>
#parent{
height: 300px;
width: 300px;
background-color: red;
}
#son{
height: 100px;
width: 100px;
background-color: green;
}
</style>
</head>
<body>
<div id="parent">
<div id="son"></div>
</div>
</body>
<script>
document.getElementById('parent').addEventListener('click',function(e){
console.log('是你爸爸')
},false)
document.getElementById('son').addEventListener('click',function(e){
console.log('你儿子')
e.stopPropagation() // 阻止冒泡
},false)
</script>
阻止冒泡行为的兼容性:
非 IE8及以下浏览器 使用 e.stopPropagation()
IE8及以下浏览器 使用 window.event.cancelBubble = true