gpt4 book ai didi

javascript - 禁用点击事件直到动画完成

转载 作者:数据小太阳 更新时间:2023-10-29 04:39:03 24 4
gpt4 key购买 nike

在我的游戏中,我有一个填充了单词的网格。要拼写单词,用户必须单击称为“拖动”的一侧的字母。单击字母时,它会动画到网格上的位置。

我遇到的问题是用户可以快速点击字母,这会导致程序崩溃。为了解决这个问题,我想在动画完成之前禁用点击事件。

过去我曾使用过 setTimeOut 函数,但它不是一种可靠的方法,因为计时完全取决于浏览器速度。

这里是点击事件:

$('.drag').on('click', function (e) {
e.preventDefault();
var target = $('.highlight-problem .drop-box:not(.occupied):first');
var targetPos = target.parents('td').position();
console.log(targetPos);
var currentPos = $(this).offset();
var b = $(this);
if (target.length) {
target.addClass("occupied");
$(".occupied").parent(".flip-wrapper").addClass("flipped");
var clonedObject = b.clone()
if (b.data("letter") == target.parents('td').data("letter")) {
clonedObject.addClass("right-letter");
target.addClass('right-letter');
setTimeout(function () {
hitSound.play();
}, 550);
} else {
clonedObject.addClass("wrong-letter");
target.addClass('wrong-letter');
setTimeout(function () {
missSound.play();
}, 550);
}
clonedObject.appendTo("table").css({
position: "absolute",
top: currentPos.top,
left: currentPos.left
}).stop().animate({
top: targetPos.top,
left: targetPos.left
}, "slow", function () {
$(this).prop('disabled', false).css({
top: 0,
left: 0
}).appendTo(target);
var spellWord = $('.highlight-problem .drop-box');
if (!spellWord.filter(':not(.occupied)').length) {
var wordIsCorrect = 0;
spellWord.each(function () {
if ($(this).parents('td').data("letter") == $(this).find("div").data("letter")) {
console.log('letter is: ' + $(this).find("div").data("letter"))
wordIsCorrect++;
}
});

最佳答案

只需简单的 3 步即可完成。

  1. 声明一个名为animationComplete 的全局变量并将其设置为false

    var animationComplete = false;
  2. 在您的 .animate({...}); 函数中,在动画完成后切换值。

    .animate({
    top: targetPos.top,
    left: targetPos.left
    }, "slow", function () {
    ...
    animationComplete = true;
    });
  3. 使用全局变量检查完整性。

    if (animationComplete)
    {
    // Do something!
    }

完整代码

JavaScript

animationComplete = true;
$(document).ready(function(){
animationComplete = false;
$(".background").animate({
height: 50,
width: 50
}, 10000, function(){
animationComplete = true;
});
$("button").click(function(){
if (animationComplete)
$(".background").animate({
height: 200,
width: 200
}, 10000, function(){
animationComplete = false;
});
else
alert("Please wait till the animation is complete!");
});
});

HTML

<div class="background"></div>
<button>Click me!</button>​

CSS

.background {background: red;}

fiddle :http://jsfiddle.net/KAryP/

在此处调整您的代码:http://jsfiddle.net/smilburn/Dxxmh/94/

关于javascript - 禁用点击事件直到动画完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13247849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com