将参数传递给 css 动画

Passing parameters to css animation

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>

也许另一种方法是使用:Element.animate()

var m = "100%";
var w = "300%";

document.getElementsByClassName('p2')[0].animate([{
        marginLeft: m,
        width: w
    },
    {
        marginLeft: '0%',
        width: '100%'
    }
], {
    duration: 2000,
});
<!DOCTYPE html>
<html>
<head>
<style>

</style>
</head>
<body>
<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>
</body>
</html>

,但是去掉了一个动画,所以很容易理解是怎么回事。

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

document.querySelector('.p2').style.setProperty('--m','100%');
   
.p1,.p2 {
  animation-duration: 3s;
  animation-name: slidein;
}

@keyframes slidein {
  from {
    margin-left: var(--m, 0%);
   
  }
  to {
    margin-left: 0%;
    
  }
}
<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>