如何使用 javascript 更改 @keyframes 值?

2023-12-01

我想要做的是改变 0% 和 100% 的最高值@keyframes取决于 javascript 中的 x 等于什么。

我之前已经使用 javascript 更改了 css,但我被困在这个上了

Code:

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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 javascript 更改 @keyframes 值? 的相关文章