jquery——解決鼠標移入移出導致盒子不停移動的bug
阿新 • • 發佈:2018-06-22
image ack style mage mouseout utf 解決 class box
使用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:
解決方法:在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>
jquery——解決鼠標移入移出導致盒子不停移動的bug