我有一个简单的 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
中的left
和top
值,使其转到我设置的设定位置动态的?
最佳答案
您可以完全使用 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/