如何使用JavaScript更改@keyframes vlaues? [英] How to change @keyframes vlaues using javascript?

查看:93
本文介绍了如何使用JavaScript更改@keyframes vlaues?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的就是根据JavaScript中的x等于来更改@keyframes的0%和100%的最大值.

What I am wanting to do is to change the top value of 0% and 100% of the @keyframes depending on what x equals in javascript.

我以前使用javascript更改过CSS,但是我被困在这个

I have changed css using javascript before but i am stuck on this one

代码:

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变量,您可以轻松地做到这一点:

Consider CSS variables and you can easily do this:

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更改@keyframes vlaues?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆