jquery——解决鼠标移入移出导致盒子不停移动的bug

时间:2023-03-09 18:38:50
jquery——解决鼠标移入移出导致盒子不停移动的bug

使用mouseover()、mouseout()时会出现这样一种情况,鼠标快速多次移入移出后这个盒子会在鼠标不动后继续运动

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
$('.box').mouseover(function () {
$(this).animate({marginTop:100});
});
$('.box').mouseout(function () {
$(this).animate({marginTop:50});
})
})
</script>
<style type="text/css">
.box{
width:300px;
height:300px;
background-color: hotpink;
margin:50px auto;
}
</style>
</head>
<body>
<div class="box" id="div"></div>
</body>
</html>

此时会有这种bug:

jquery——解决鼠标移入移出导致盒子不停移动的bug

解决方法:在mouseover()和mouseout()前面加上stop()就好啦!

    <script type="text/javascript">
$(function () {
$('.box').mouseover(function () {
$(this).stop().animate({marginTop:100});
});
$('.box').mouseout(function () {
$(this).stop().animate({marginTop:50});
})
})
</script>