[英]How can I fix the warping issue in jQuery?
我的蓝鱼应该怎么做: 移动到屏幕上的随机位置,当你用鼠标触摸它时,它应该快速逃到一个随机位置,然后继续游泳。
我的蓝鱼会做什么:逃跑后,它会扭曲到一个随机位置。
如何修复翘曲,以便鱼在逃跑后从当前位置继续游动?
/*globals $:false, window:false*/ $("#blueFishId").animate({}, function() { blueFish(this) }); function blueFish(IdRef) { var x = Math.floor(Math.random() * ($(window).width() - $(IdRef).width())) var y = Math.floor(Math.random() * ($(window).height() - $(IdRef).height())) $(IdRef).delay(500).animate({ top: y, left: x }, 5000, function() { blueFish(IdRef); }); } $("#blueFishId").on("mouseenter", function() { var x = Math.floor(Math.random() * ($(window).width() - $("#blueFishId").width())) var y = Math.floor(Math.random() * ($(window).height() - $("#blueFishId").height())) $("#blueFishId").animate({ top: y, left: x }, 1000); });
img { position: relative; } #blueFishId { height: auto; width: auto; position: relative; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <img class="blueFish" id="blueFishId" src="images/fish2.png">
要解决此问题,您需要在鼠标悬停时清除排队动画,并且还需要停止正在执行的当前动画。 您可以通过调用stop()
并将delay()
调用放在animate()
后来实现这一点。 另请注意,在stop()
当前动画后,您可以通过在mouseenter
内调用您的函数来完成逻辑。 尝试这个:
var $fish = $('#blueFishId'); function moveFish($fish) { var x = Math.floor(Math.random() * ($(window).width() - $fish.width())) var y = Math.floor(Math.random() * ($(window).height() - $fish.height())) $fish.animate({ top: y, left: x }, 5000, function() { moveFish($fish); }).delay(500); } $fish.on("mouseenter", function() { $fish.stop(true); moveFish($fish); }); moveFish($fish);
img { position: relative; } #blueFishId { height: auto; width: auto; position: relative; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <img class="blueFish" id="blueFishId" src="images/fish2.png">
您可能还需要考虑让鱼在mouseenter
上移动更远的距离,使其看起来更像是在“逃离”鼠标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.