gpt4 book ai didi

javascript - 如何使用 javascript 更改@keyframes 值?

转载 作者:行者123 更新时间:2023-11-28 15:06:44 29 4
gpt4 key购买 nike

我想做的是根据 javascript 中的 x 等于什么来更改 @keyframes 的 0% 和 100% 的最高值。

我以前使用 javascript 更改过 css,但我卡在了这个上

代码:

var x = Math.floor((Math.random() * 1080) + 1);
div {
width: 100px;
height: 100px;
background-color: red;
position: relative;
-webkit-animation-name: example; /* Safari 4.0 - 8.0 */
-webkit-animation-duration: 4s; /* Safari 4.0 - 8.0 */
animation-name: example;
animation-duration: 4s;
}


@keyframes example {
0% {left:0px; top:300px}
100% {left:830px; top:0px}
}
 <div></div>

最佳答案

考虑 CSS 变量,您可以轻松地做到这一点:

var x = Math.floor((Math.random() * 300) + 1);
console.log(x);
var root = document.querySelector(':root');
root.style.setProperty("--top",x+"px");
:root {
--top: 0;
}

div.box {
width: 100px;
height: 100px;
background-color: red;
position: relative;
-webkit-animation-name: example;
/* Safari 4.0 - 8.0 */
-webkit-animation-duration: 4s;
/* Safari 4.0 - 8.0 */
animation-name: example;
animation-duration: 4s;
}

@keyframes example {
0% {
top: var(--top);
}
100% {
top: 0;
}
}
<div class="box"></div>

关于javascript - 如何使用 javascript 更改@keyframes 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49244608/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com