LoginSignup
12
11

More than 5 years have passed since last update.

jQuery.animate() の transform 対応版を簡単に作る

Last updated at Posted at 2018-05-12

概要

jQuery.animate() は大変便利ですが、
回転させるために { transform: 'rotate(360deg)' }
とか渡しても transform に未対応であるため動きません。
そこで、tranform にも対応可能な animate2() をパパっと作ってしまいます。

まずは関数作成

$.fn.animate2 = function (properties, duration, ease) {
    ease = ease || 'ease';
    var $this = this;
    var cssOrig = { transition: $this.css('transition') };
    return $this.queue(next => {
        properties['transition'] = 'all ' + duration + 'ms ' + ease;
        $this.css(properties);
        setTimeout(function () {
            $this.css(cssOrig);
            next();
        }, duration);
    });
};

これだけ。これで jQuery の関数を増やせます。
最低限の実装になってるので必要に応じて、拡張してください。

使い方

$('.something')
    .css({ top: 0 })
    .animate2({ top: '100px' }, 200) //下に移動
    .animate2({ transform: 'rotate(360deg)' }, 200) //1回転
;

これだけ。animate() の代わりに animate2() を使えばOKです。

説明

jQuery の animate() の代わりに transition を使っています。

transition を使うことでアニメーションがスムーズになりうるという良い副作用もあります。
(transition はブラウザに動きを前もって伝えることができ、多くのブラウザで描画の際、GPU で最適化する仕様になっている。)

12
11
0

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
12
11