【问题标题】:Passing parameters to css animation将参数传递给css动画
【发布时间】:2018-04-10 09:47:17
【问题描述】:
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 的参数传递。

【问题讨论】:

  • 不确定您是否可以直接执行此操作,但您可以使用 javascript 设置一个 css 变量,然后在您的 @keyframes 中使用此变量

标签: css css-animations keyframe


【解决方案1】:

使用 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>

【讨论】:

  • 请注意,如果

    (或

    )的位置设置为相对位置,这不起作用(至少对我而言)
【解决方案2】:

也许另一种方法是使用: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>

【讨论】:

    【解决方案3】:

    Temani Afif's answer, 但是删除了一个动画,所以很容易理解发生了什么。

    使用 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>

    【讨论】:

    • 我看不出这个答案对问题有什么影响。你读过它吗?您只是删除了我答案的一部分。我看不出您做了什么简化,因为您使用的是完全相同的技术
    • 我的意思是,当我第一次阅读您的答案时,我很难理解它,因为有两个变量同时发生变化。这不是你的错,我很感谢你的回答,但我想如果我删除一个动画,那么读者理解发生的事情会容易得多。
    • @TemaniAfif 我应该说这是你的答案,没有缩放效果(就像现在一样),但我把它写成“类似于 Temani Afif 的答案”。我的错。
    • 也许让我很难理解发生了什么的原因是因为我是 css 和 javascript 的新手。
    猜你喜欢
    • 2022-08-14
    • 2013-07-27
    • 2017-08-10
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    相关资源
    最近更新 更多