LoginSignup
97
89

More than 5 years have passed since last update.

CSSアニメーションの終了に合わせて処理を行いたい

Last updated at Posted at 2014-07-24

やりたかったこと

画像をアニメーションで動かし、アニメーション終了後にボタンを出現させる

最初に思いついたやり方

jsのsetTimeoutを使ってアニメーションの終了に合わせてクラスを切り替えればいっか

main.css
.anm_spin{
    -webkit-animation: spin 4s;
}
@-webkit-keyframes spin{
  0% { -webkit-transform :rotateY(0deg);opacity:0; }
  50% { -webkit-transform :rotateY(0deg);opacity:1; }
  100% { -webkit-transform :rotateY(1080deg); }
}

.hidden{
    display: none;
}

初期状態でボタンはdisplay:none;にしている。4秒間のアニメーションなので・・・

main.js
$(function(){
    setTimeout(function(){
        $(".button").removeClass("hidden");
    },4000);
});

4秒後にdisplay:none;にするためのclassを削除する。

index.html
<div>
  <div class="anm_wrap">
    <img src="img/card.png" alt="card" width="150" class="anm_spin">
  </div>
  <div class="button hidden">
    <a href="#">button</a>
  </div>
</div>

問題点

1つのアニメーションなら問題ないが、2つ以上のアニメーションを複合させたり複雑になってくると変更が手間。
スマホなどのブラウザの場合、処理速度の問題でずれてくるかもしれないという懸念。

調べた結果

keyframesアニメーションの開始、終了時にイベントが発行されるのでそれを使える
※webkit系のブラウザの場合です.。firefoxであれば下記のようにしてください。
webkitAnimationStart→AnimationStart
webkitAnimationEnd→AnimationEnd

$(function(){
    $(".anm_spin").on('webkitAnimationStart', function(){
        //.anm_spinのアニメーション開始時の処理
    });
    $(".anm_spin").on('webkitAnimationEnd', function(){
        //.anm_spinのアニメーション終了時の処理
    });
});

今回ならこういう風に書けばいいみたい

main.js
$(function(){
    $(".anm_spin").on('webkitAnimationEnd', function(){
        $(".button").removeClass("hidden");
    });
});

LINK

同じような話で、こちらにCSSTransitionでのイベント取得について書かれていました。
CSSTransitionのイベントが終わった時に何かの処理をする
http://qiita.com/roana0229/items/b1d3ac9038ff59ce1e0f

97
89
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
97
89