3

キーを押してdivをアニメーション化していますが、上矢印を2回押すとアニメーションが壊れます。1秒後にのみキーを押すことができる方法はありますか?

$(document).keyup(function(e){
    if (e.keyCode == 38) { 
        $('.selected').animate({'top':'300px'},500);
        $('.section.selected').removeClass('selected')
                              .next('.section').animate({'top':'0'},500)
                              .addClass('selected');
        return false;
    }
    e.preventDefault();
});
4

4 に答える 4

1

要件を可能な限り文字通り実装するには、次のようにします。

var allowKeyPress = true;
$(document).keyup(function(e){
if (e.keyCode == 38) { 
    if (!allowKeyPress)
        return false;
    allowKeyPress = false;
    setTimeout(function() { allowKeyPress = true; }, 1000);

    $('.selected').animate({'top':'300px'},500);
    $('.section.selected').removeClass('selected').next('.section').animate({'top':'0'},500).addClass('selected');
    return false;    
  }    
  e.preventDefault();
});

つまり、フラグを使用します。allowKeyPressキーアップテストでフラグがfalseであるかどうかをテストし、そうである場合はすぐに停止します。それ以外の場合は、続行し、フラグをに設定し、falseを使用setTimeout()して1秒後に実行する関数をスケジュールし、フラグをに戻しtrueます。もちろん、アニメーションを実行します。

于 2013-03-26T11:56:06.543 に答える
1

さらにアニメーションをトリガーする前に、要素がアニメーション化されているかどうかを確認してください。

$(document).keyup(function(e){
  if (e.keyCode == 38) { 
    if(!$('.selected').is(':animated')){

      $('.selected').animate({'top':'300px'},500);       
      $('.section.selected').removeClass('selected').next('.section').animate({'top':'0'},500).addClass('selected');
      return false;
    } 
  }    
  e.preventDefault();
});
于 2013-03-26T11:59:52.053 に答える
0

これを試して:

$(document).keyup(function(e){
     if (e.keyCode == 38 && !$('.selected').is(':animated')) { 
          $('.selected').animate({'top':'300px'},500);
          $('.section .selected').removeClass('selected')
                               .next('.section')
                               .animate({'top':'0px','position':'relative'},500)
                               .addClass('selected');
          return false;
      }
      e.preventDefault();
});
于 2013-03-26T11:58:44.920 に答える
0

要素のいずれかがアニメーション化されているかどうかを確認し、新しいアニメーションをキャンセルできます。したがって、キーアップ関数の最初の行として以下のコードを入力します。

if($(".selected").is(":animated")) return;
于 2013-03-26T11:59:58.217 に答える