css - 将参数传递给 css 动画

标签 css css-animations keyframe

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 传递。

最佳答案

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

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 - 将参数传递给 css 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49750473/

相关文章:

javascript - 如何使此图像 slider 响应?

css - 旋转 7 次然后缓动

css - 在 CSS 中重新创建 MS Windows Phone Tiltin 动画

encoding - 视频编码和关键帧

css - 有没有什么办法可以根据它们的位置对 CSS 进行正则表达式来增加属性值?

css - 网络应用 CSS 问题

php - 仅显示 DIV HOMEPAGE

javascript - 如何同步具有不同样式溢出的div的两个滚动条

jquery - CSS/jQuery 动画定位问题

css - 卡住关键帧动画以进行调试