mouseenter、mouseleave与mouseover、mouseout都是处理鼠标的移入移出事件
二者的本质区别在于,mouseenter、mouseleave不会冒泡,简单的说,它不会被它本身的子元素的状态影响到.但是mouseover、mouseout就会被它的子元素影响到,在触发子元素的时候,mouseover、mouseout会冒泡触发它的父元素 (想要阻止mouseover、mouseout的冒泡事件就用mouseenter、mouseleave)
共同点:当二者都没有子元素时,二者的行为是一致的,但是二者内部都包含子元素时,行为就不同了
如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
#father {
width: 200px;
height: 200px;
background-color: red;
display: flex;
justify-content: center;
align-items: center;
margin: 50px auto;
}
#son {
width: 100px;
height: 100px;
background-color: yellow;
}
</style>
<body>
<div id="father">
<div id="son"></div>
</div>
<script>
let father = document.querySelector('#father');
father.onmouseenter = function () {
console.log('mouseenter');
};
father.onmouseleave = function () {
console.log('mouseleave');
};
father.onmouseover = function (event) {
console.log('mouseover');
};
father.onmouseout = function (event) {
console.log('mouseout');
};
</script>
</body>
</html>
以上代码创建两个父子关系的div,给#out分别绑定mouseenter、mouseleave与mouseover、mouseout事件,将鼠标从左至右滑过观察控制台打印结果:
可以发现当鼠标划过#father左侧边框时出发了mouseover与mouseenter事件,紧接着划过#son左侧边框时触发了mouseout与mouseover事件,划过#son右侧边框时又触发了mouseout与mouseover事件,直达最后移出#father时触发了mouseout与mouseleave事件。mouseenter与mouseleave只在鼠标从#father移入、移出时才会触发,而mouseover与mouseout不但会在#father移入移出触发,还会在子节点#son移入移出时触发。
从例子中我们就可以真正看到这两个事件的不同了,当绑定事件的元素里面有子元素的时候,鼠标经过绑定mouseover的当前元素以及它里面的子元素的时候,都会触发,而经过绑定mouseenter的元素时,只会在鼠标刚进入的时候触发,当进入其子元素的时候,是不会再触发的了