Event事件之阻止事件冒泡
阻止事件冒泡
mouseover 和 mouseout事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div{
width: 200px;
height: 200px;
background: red;
margin: 100px auto;
}
p{
width: 100px;
height: 100px;
background: blue;
margin: 50px;
}
</style>
</head>
<body>
<div>
<p></p>
</div>
<script>
var div=document.querySelector('div');
div.addEventListener('mouseover',function(){
console.log('移入了')
})
div.addEventListener('mouseout',function(){
console.log('移出了')
})
</script>
</body>
</html>
我们发现从div移入其子元素p标签,还会打印“移出了”,再打印“移入了”,再将其移入div,还会打印“移出了”,再打印“移入了”。
结论:如果鼠标移入或者移出 子元素 范围 ,mouseover 和 mouseout 会触发~
mouseenter和 mouseleave事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div{
width: 200px;
height: 200px;
background: red;
margin: 100px auto;
}
p{
width: 100px;
height: 100px;
background: blue;
margin: 50px;
}
</style>
</head>
<body>
<div>
<p></p>
</div>
<script>
var div=document.querySelector('div');
div.addEventListener('mouseenter',function(){
console.log('移入了')
})
div.addEventListener('mouseleave',function(){
console.log('移出了')
})
</script>
</body>
</html>
我们发现从div移入其子元素p标签,就没有任何反应了。
结论:mouseenter 和 mouseleave 不受 子级元素范围干扰~
取消冒泡
有的需求可能需要执行元素本身的事件,不需要执行父级身上的事件。这个时候就需要我们取消冒泡事件了。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div{
width: 200px;
height: 200px;
background: red;
margin: 100px auto;
}
p{
width: 100px;
height: 100px;
background: blue;
margin: 50px;
}
</style>
</head>
<body>
<div>
<p></p>
</div>
<script>
var div=document.querySelector('div');
var p=document.querySelector('p');
div.addEventListener('click',function(){
alert('div')
})
p.addEventListener('click',function(e){
alert('p')
})
</script>
</body>
</html>
假设我们需要点击p标签的时候,只需要显示打印“p”的对话框怎么整?
### cancelBubble ---
var div=document.querySelector('div');
var p=document.querySelector('p');
div.addEventListener('click',function(){
alert('div')
})
p.addEventListener('click',function(e){
// 取消事件冒泡
e.cancelBubble = true;
alert('p')
})
要实现点击哪个,就去执行哪个标签的对应事件:
stopPropagation
var div=document.querySelector('div');
var p=document.querySelector('p');
div.addEventListener('click',function(){
alert('div')
})
p.addEventListener('click',function(e){
// 取消事件冒泡
e.stopPropagation()
alert('p')
})
cancelBubble和stopPropagation的区别:
cancelBubble:这是ie最早之前支持的方法,后期的时候谷歌和火狐才支持它了,原本它其实不在标准规范里,它兼容性非常好支持ie老版本,如果仅考虑兼容性可以使用它。
stopPropagation:这是标准W3C标准,建议在现代的浏览器使用。
(后续待补充)