mouseenter事件不会冒泡 mouseleave事件不会冒泡
mouseover事件会冒泡 mouseout事件会冒泡
(不懂冒泡的可以查看冒泡事件的相关博客,但是看完我举的例子大概就能理解什么是冒泡,看懂mouseenter和mouseover就知道mouseleave和mouseout事件的区别了)
简答来说冒泡就是把父级元素的事件传递到子级标签,这样子级元素也具有了父级元素的事件。
用一个简单的案例来演示。
1.当事件为mouseover时:
当鼠标移动到类名为father的元素中,控制台会输出一句:我是mouseover,我会冒泡!
当我鼠标移动到类名为son的元素中,控制台同样会输出:我是mouseover,我会冒泡!
2.当事件为mouseenter时:
鼠标只有移动到对应添加事件的元素,才会触发事件。只有当鼠标移动到类名为father的元素上才会在控制台输出提示。所以当鼠标移动到类名为son的元素时,控制台不会输出提示。
这里是当事件是mouseover的代码,要是不清楚哪一个事件可以复制后修改事件尝试尝试。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.father {
width: 100px;
height: 100px;
background-color: pink;
}
.son {
margin-left: 50px;
width: 50px;
height: 50px;
background-color: skyblue;
}
</style>
</head>
<body>
<div class="father">
father
<div class="son">
son
</div>
</div>
<script>
var father = document.querySelector('.father');
father.addEventListener('mouseover', function () {
console.log('我是mouseover,我会冒泡!');
})
</script>
</body>
</html>
下图是访问了father和son之后输出的语句。