概要
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 で最適化する仕様になっている。)