将参数传递给CSS动画 [英] Passing parameters to css animation

查看:54
本文介绍了将参数传递给CSS动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

p {
  animation-duration: 3s;
  animation-name: slidein;
}

@keyframes slidein {
  from {
    margin-left: 100%;
    width: 300%; 
  }

  to {
    margin-left: 0%;
    width: 100%;
  }
}

对于上面的动画CSS代码,我想知道是否有任何方法可以将margin-leftwidth的值作为Javascript的参数传递.

For the animation CSS code above, I'm wondering whether there's any way to pass the values of margin-left and width as parameter from Javascript.

推荐答案

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

Use CSS variables and you can easily do this:

document.querySelector('.p2').style.setProperty('--m','100%');
document.querySelector('.p2').style.setProperty('--w','300%');

.p1,.p2 {
  animation-duration: 3s;
  animation-name: slidein;
}

@keyframes slidein {
  from {
    margin-left: var(--m, 0%);
    width: var(--w, 100%);
  }
  to {
    margin-left: 0%;
    width: 100%;
  }
}

<p class="p1">
 This will not animate as the animation will use the default value set to the variable
</p>
<p class="p2">
  This will animate because we changed the CSS variable using JS
</p>

这篇关于将参数传递给CSS动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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