【javascript】CSSのアニメーション@keyframesをjavascriptで制御する setProperty
CSSだけのアニメーション
.box{
width: 10px;
height: 30px;
background: black;
animation: progress 3s ease infinite;
}
@keyframes progress {
100%{
width: 100%;
height:100px;
background: red;
}
}
参考
【CSS】animation パート1
最低限の設定とアニメーション時間(duration)と繰り返し(infinite)について
【CSS】animation パート2
アニメーションの動き(time-function),遅延時間(delay),方向(direction)について
CSSのカスタムプロパティ
- :root{}で初期値を設定
- --名で変数を指定
- var(--名)と記述し、ここに値を代入する。
:root { /* 初期値 */
--width: 100%;
--height: 30px;
--background: black;
}
.box{
width: 10px;
height: 30px;
background: black;
margin: 50px 0;
animation: progress 3s ease infinite;
}
@keyframes progress {
100%{
width: var(--width);
height: var(--height);
background: var(--background);
}
}
javascriptでCSSで指定した変数を制御する
セレクトボックスを選択しても変化がない場合は右をクリック!
以下の下線部を書き換えます。
HTML
<div class="wrapper">
<div class="box"></div> <!-- アニメーションする要素 -->
</div>
<!-- onchangeでセレクトボックスに変更があったら、値を取得し処理 -->
<select name="--width" id="--width" onchange="selected(this.id, this.value)">
<option value="100%" selected>width: 100%</option>
<option value="50%">width: 50%</option>
<option value="30%">width: 30%</option>
</select>
<select name="--height" id="--height" onchange="selected(this.id, this.value)">
<option value="30px" selected>height: 30px</option>
<option value="50px">height: 50px</option>
<option value="100px">height: 100px</option>
</select>
<select name="--background" id="--background" onchange="selected(this.id, this.value)">
<option value="black" selected>background: black</option>
<option value="red">background: red</option>
<option value="blue">background: blue</option>
</select>
参考
【javascript】onclickの書き方と使い方 クリックした値を取得する
javascript
- setProperty(第一引数 ,第二引数 )
- 第一引数は、CSSカスタムプロパティ(--名)
- 第二引数は、変数の値
function selected(id, value){
// selectボックスの値を取得し、setPropertyに代入
document.documentElement.style.setProperty(id, value);
}