mouseover与mouseenter,mouseout和mouseleave的区别
mouseover与mouseenter,mouseout和mouseleave的区别
Introdece
想起来这个就来气。举个例子,做轮播图的时候,当鼠标移动到前后的按钮的时候要清除掉定时器。我的dom结构是这样的。
于是乎,我就在container上绑定了函数,当移动到上面时,清除定时器函数,移开时增加。 我还在dot-container上也绑定了同样的函数,下面我来阐述下,我一脸懵逼的结果
-
鼠标不经过buttuon划入轮播图图片的时候,正常的停止和运动
-
鼠标移动到button上,不清除定时器,划出也无效
-
鼠标滑动到dot图标上,清除定时器,划出dot,但是还没出conatiner,增加定时器。。。emmmm
-
当时就看着傻帽一样的轮播图,。瞎几把动。。。
principle
其实本质就是我函数没绑定正确,也是基础属性掌握的不熟练。
mouseover事件:不论鼠标指针穿过被选元素或其子元素,都会触发 mouseover 事件。
mouseenter事件:只有在鼠标指针穿过被选元素时,才会触发 mouseenter 事件。
mouseout事件:不论鼠标指针离开被选元素还是任何子元素,都会触发 mouseout 事件。
mouseleave事件:只有在鼠标指针离开被选元素时,才会触发 mouseleave 事件。
做个demo吧
<!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>
.big {
width: 500px;
height: 500px;
background: red;
}
.small {
width: 100px;
height: 100px;
background: blue;
}
</style>
</head>
<body>
<!-- mouseover mouseout -->
<div class="big">
<div class="small">
</div>
</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<!-- mouseenter mouseleave -->
<div class="big">
<div class="small">
</div>
</div>
<script>
// mouseover mouseout
var big = document.getElementsByClassName("big")[0],
big2 = document.getElementsByClassName("big")[1];
big.addEventListener("mouseover", function() {
console.log(1);
})
big.addEventListener("mouseout", function() {
console.log(2);
})
// mouseenter mouseleave
big2.addEventListener("mouseenter", function() {
console.log(3);
})
big2.addEventListener("mouseleave", function() {
console.log(4);
})
</script>
</body>
</html>
话说做的,真丑啊。哎。。。 我就随便做个demo啊。
phenomenon
- 对于mouseover和mouseout来说。我绑定滑入的时候console.log(1),划出的时候console.log(2)
很好理解,从外部移入到红色区域时,触发了1,当移动到蓝色区域时,它相对红色的已经移出了,所以触发了离开函数,打印了2.但是对于蓝色来说,他又进去了。所以再次触发打印了1.
这就是我当时遇到的最主要的问题。。。emmmm
同理,当我移出时
首先离开蓝色,2 。进入红色1,离开红色 2.
你设想一下, 如果你想设置一个变量,当进入这块区域就加1.如果。是这种情况。。会不会加了很多次。。。。。。。
- 对了mouseenter和mouseleave,这个就简单多了
只触发一次。
同理,3是第一次进入的时候的。
Review
mouseover事件:不论鼠标指针穿过被选元素或其子元素,都会触发 mouseover 事件。
mouseenter事件:只有在鼠标指针穿过被选元素时,才会触发 mouseenter 事件。
mouseout事件:不论鼠标指针离开被选元素还是任何子元素,都会触发 mouseout 事件。
mouseleave事件:只有在鼠标指针离开被选元素时,才会触发 mouseleave 事件。
writer&contact
{
"name":"Jontyy" ,
"email": " [email protected]"
}