【Animate.css】クリックでアニメーションさせる方法

「Animate.css」のアニメーションをクリックまたはタップ動作で開始させる方法です
色々な方法が考えられますが
- クリックでclassを付与してアニメーション開始
- アニメーション終了でclassを解除
が、一番お手頃かな思います
目次
JavaScriptでの動作サンプル
See the Pen Animate.css Click Ivent by yochans (@yochans) on CodePen.
JavaScriptでのサンプルコードと説明
html
<div><p class="animated">BOUNCE</p></div>CSS
div{
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  margin:50px 0;
}
.animated{
  width:120px;
  padding: 6px;
  background-color: #01579B;
  color:#FFF;
}JavaScript
//対象のclassを定義
let item = document.getElementsByClassName('animated');
//クリック時にclassを追加してアニメーション開始
item[0].addEventListener('click', () => {
    item[0].classList.add('bounce');
    }, false);
//アニメーション終了時にclassを削除
item[0].addEventListener('animationend', () => {
    item[0].classList.remove('bounce');
    }, false);※classでイベント取得していますが、複数の要素にアニメーション処理を入れる予定でなければ、getElementById()でid指定した方がシンプルになります
addEventListener('click’, 実行関数, false);
クリック検出イベントを実装
classなので対象がひとつであってもjQueryと違い、class名[0]の記述が必要となるので注意です
複数設置時はfor文などで回して、全てに定義すればOK
addEventListener('animationend’, 実行関数, false);
'animationend’はanimationでのCSSアニメーションが終了した時に発火するイベントです
アニメーション開始時であれば’animationstart’で発火イベントが作成可能です
また、transitionでのアニメーション発火の場合は’transitionstart’や’transitionend’になります
classList.add('bounce’);
クリックされた要素に「Animate.css」のアニメーションclassを追加してアニメーションを開始します
classList.remove('bounce’);
アニメーション終了後に追加したアニメーションclassを要素から除去します
追記
アニメーション終了イベントを記述しなくても開始前にクラスを一回外せば良いだけだった?
jQueryでの動作サンプル
See the Pen Animate.css Click Ivent(jQuery) by yochans (@yochans) on CodePen.
jQueryでのサンプルコードと説明
jQuery
//クリックイベント
$('.animated').click(function() {
        //アニメーションclassを追加
        this.classList.add('bounce');
        //アニメーション終了時にclassを削除
        this.addEventListener('animationend', () => {
    this.classList.remove('bounce');
    }, false);
});




ディスカッション
コメント一覧
まだ、コメントがありません