書いたやつ
https://github.com/clngn/animation-study
これを真似た。トグルボタンはめんどかったので諦めた。
https://dribbble.com/shots/1749645-Contact-Sync
パッケージ
https://github.com/web-animations/web-animations-js
最初動かなかったから入れたけど、最終的にはなくてもわりと動きそうな気がした(Chrome利用)。
アニメーション
const element = document.querySelector('.animation');
const animation = element.animate([
{
width: '10px',
height: '10px',
opacity: 0,
},
{
width: '50px',
height: '50px',
opacity: 1,
}
], {
duration: 500,
easing: 'ease-out',
});
animateの第一引数はkeyframes、第二引数はotions。
keyframesは配列に変化前と変化後のstyleを入れる。
両方のプロパティを揃えておかないとダメっぽい。
optionsはdurationやeasingなどが指定できる。
後処理
コメントで指摘いただき、animateのoptionsで調整できることがわかったので修正。
...
], {
duration: 500,
easing: 'ease-out',
fill: 'forwards',
});
普通にanimateさせただけだとアニメーション終了時にもとのスタイルに戻る。
変化させたあとの状態を維持したい場合は終了時にスタイルを上書きする必要がある。
// 上の続き
animation.onfinish = () => {
element.style = {
width: '50px',
height: '50px',
opacity: 1,
};
};
感想
JS内でスタイルいじるなら最初からCSS in JSでやった方が良いのでは?感があった。
それはそれでいろいろ面倒ごとありそうな気もするけど。