jQueryで要素をアニメーションさせている時に、別のアニメーションを発生させないようにする方法をメモ。
通常時のサンプルコード
HTML
#buttonをクリックすると、.boxが移動するサンプルです。
<button id="button">アニメーション実行</button> <div class="box"></div>
CSS
.box {
position: absolute;
top: 50px;
left: 50px;
}
JavaScript
$(function() {
$(document).on('click', '#button', function() {
$('.box').animate({
top: 100,
left: 300
}, 1000).animate({
top: 50,
left: 50
}, 1000);
});
});
この場合、アニメーション中にボタンをクリックすると、クリックした回数だけアニメーションが行われます。
アニメーションしていない要素を対象にする
JavaScript
$(function() {
$(document).on('click', '#button', function() {
$('.box').not(':animated').animate({
top: 100,
left: 300
}, 1000).animate({
top: 50,
left: 50
}, 1000);
});
});
$(‘.box’).not(‘:animated’)とすることで、アニメーションしていない.boxに対してアニメーションを指定する形になるため、動いている間は対象から外されます。
要素がアニメーション中かどうかを確認する
JavaScript
$(function() {
$(document).on('click', '#button', function() {
if(!$('.box').is(':animated')){
$('.box').animate({
top: 100,
left: 300
}, 1000).animate({
top: 50,
left: 50
}, 1000);
}
});
});
if文で.boxがアニメーション中でないかを見て、アニメーション中でない場合にアニメーションを実行します。
アニメーションを変数で管理する
JavaScript
$(function() {
var animateFlag = false;
$(document).on('click', '#button', function() {
if(!animateFlag) {
animateFlag = true;
$('.box').animate({
top: 100,
left: 300
}, 1000).animate({
top: 50,
left: 50
}, 1000, function() {
animateFlag = false;
});
}
});
});
animateFlagがfalseの時だけアニメーションを実行するようにします。
1回実行されるとanimateFlagをtrueにして、完了時に再びanimateFlagをfalseに戻します。
コメントが承認されるまで時間がかかります。