簡體   English   中英

如何解決 jQuery 中的翹曲問題?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM