mouseover:当鼠标移入元素或其子元素都会触发事件,所以有一个重复触发,冒泡过程。对应的移除事件是mouseout
mouseenter:当鼠标移除元素本身(不包含元素的子元素)会触发事件,也就是不会冒泡,对应的移除事件是mouseleave
mouseover和mouseenter的异同体现在两个方面:
1. 是否支持冒泡
2.事件的触发时机
运行下面的代码,我们可以直观的发现两者的区别:
<!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>
* {
padding: 0;
margin: 0;
}
.father {
/* margin: 100px auto; */
width: 500px;
height: 500px;
background-color: pink;
}
.son {
width: 200px;
height: 200px;
background-color: purple;
/* transform: translateX(-50px); */
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
<script>
let father = document.querySelector('.father')
let son = document.querySelector('.son')
// 事件捕获
// mouseenter——不支持事件冒泡
father.addEventListener('mouseenter', function() {
console.log('father-mouseenter')
})
son.addEventListener('mouseenter', function(e) {
// e.stopPropagation()
console.log('son-mouseenter')
})
// mouseleave——支持事件冒泡
// father.addEventListener('mouseleave', function() {
// console.log('father-mouseleave')
// })
// son.addEventListener('mouseleave', function(e) {
// // e.stopPropagation()
// console.log('son-mouseleave')
// })
</script>
</body>
</html>
mouseenter事件的情况:
当鼠标从元素的边界之外移入元素的边界之内时,事件被触发。而鼠标本身在元素边界内时,要触发该事件,必须先将鼠标移出元素边界外,再次移入才能触发。
mouseover事件的情况:
当鼠标从元素的边界之外移入元素的边界之内时,事件被触发。如果移到父元素里面的子元素,事件也会被触发
所以我们在使用鼠标经过事件一般会使用
mouseenter 和 mouseleave 没有冒泡效果(推荐)
而mouseover 和 mouseout 会有冒泡效果
以上希望可以对你有所帮助!!!
