javascript - 如何通过 JavaScript 操作 CSS @keyframes?

标签 javascript css

我有一个简单的 CSS 动画:

<div id="saved-test">

<style type="text/css">
    #saved-test {
        width:  40px; height:  40px;
        background:  red;
        position: fixed;
        top:  0; left: 0;
        animation-name: move-to-bottom;
        animation-duration: 5s;
        z-index:  1000;
    }


    @keyframes move-to-bottom {
      to {
        left:  400px;
        top:  500px;
      }
    }
</style>

这很有效,而且它可以很好地按照我想要的方式移动。我遇到的问题是,我想将此元素的目的地设置为不同的。它将“移动”到底部导航栏,这意味着目标左侧/顶部位置将根据屏幕尺寸而变化。

是否可以通过Javascript修改keyframe中的lefttop值,使其转到我设置的设定位置动态的?

最佳答案

您可以完全使用 JavaScript 编写关键帧,如下所示,这使您能够使用动态值。

The Element interface's animate() method is a shortcut method which creates a new Animation, applies it to the element, then plays the animation. It returns the created Animation object instance. More and MDN's doc.

document.getElementById("saved-test").animate(
  [
    // étapes/keyframes
    {
      left: "0px",
      top: "0px"
    },
    {
      left: 400 + "px", // you can set it dynamically
      top: 500 +"px" // you can set it dynamically
    }
  ],
  {
    duration: 5000,
    iterations: Infinity
  }
);
#saved-test {
  width: 40px;
  height: 40px;
  background: red;
  position: fixed;
  z-index: 1000;
}
<div id="saved-test">

关于javascript - 如何通过 JavaScript 操作 CSS @keyframes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72570299/

相关文章:

javascript - 从另一个文件调用函数并在完成后获取结果?

javascript - 在ajax中的div中追加返回值

javascript - 为什么函数会在对象字面量中自调用?

jquery - 将 CSS 添加到特定类,这很奇怪

html - 为什么这个DIV没有收缩包装?

javascript - Carousal - 显示元素高度动态

javascript - 为什么将注释的开头向下移动一行空格会破坏此 JavaScript 代码在 WordPress 中的编译?

javascript - 如何通过类名onclick打开特定的div

css - 中文字体无法正确呈现

html - Safari 6.1 隐藏内部 div,当外部 div 的位置为 :fixed and overflow:auto