简体   繁体   中英

How can I fix the warping issue in jQuery?

What my blue fish should do: Move around to random positions on the screen and when you touch it with the mouse, it should flee to a random location fast, then continue swimming.

What my blue fish does: After fleeing, it warps to a random location.

How can I fix the warping, so that the fish continues swimming from its current position after fleeing?

 /*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">

To fix this you need to clear the queued animation on mouseover and you also need to stop the current animation that's executing. You can achieve this by calling stop() and also putting the delay() call after the animate() . Also note that you can DRY up the logic by just calling your function from within mouseenter after you stop() the current animation. Try this:

 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">

You may also want to consider making the fish move a greater distance on mouseenter to make it look more like it's 'fleeing' the mouse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM