【发布时间】:2025-12-07 12:00:01
【问题描述】:
我正在尝试为游戏中的对象设置动画,在该游戏中,球应该在按下用户按钮时向上、向右、向左和向下移动。我试图通过在球上使用 .animate() 函数来实现这一点。但是在每个动画事件之后,球都会重置到它的初始位置,并且不会继续从它的“新”位置移动。有没有办法做到这一点?
为简单起见,以下是我的压缩代码 sn-p:
/* Animation */
var item = document.getElementById('item');
var anim;
function myMoveLeft(){
anim=item.animate([
// keyframes
{ transform: 'translateX(0px)' },
{ transform: 'translateX(-60px)' }
], {
duration: 1000,
iterations: 1
});
}
function myMoveDown(){
anim=item.animate([
// keyframes
{ transform: 'translateY(0px)' },
{ transform: 'translateY(60px)' }
], {
duration: 1000,
iterations: 1
});
// anim.onfinish(()=>{console.log("onfinish ran")})
}
item.addEventListener('animationend', () => {
console.log('Animation ended');
});
button{
display:inline-block;
height:40px;
width:80px;
}
#myContainer {
width: 400px;
height: 400px;
position: relative;
background: lightgray ;
}
#item {
background: orange;
position: absolute;
right:30px;
top:30px;
height: 30px;
width: 30px;
border-radius:50%;
}
<p>
<button onclick="myMoveLeft()">Left</button>
<button onclick="myMoveDown()">Down</button>
</p>
<div id ="myContainer">
<div id="item"></div>
</div>
正如所见,我已经尝试过使用 .onfinish() 和事件监听器 'animationend' 希望我可以更新新的 'right' 和 'top' 位置,但它不起作用。不确定这是否是正确的方法。
有人可以建议如何将元素保存到新位置并从该新位置进一步对其进行动画处理吗?
PS:如果您觉得还有其他更好的方法可以做到这一点,我也愿意接受建议/技术。
非常感谢提前!!
【问题讨论】:
-
我自己也遇到了。唯一对我有用的是设置与动画持续时间完全相同的超时,并在超时回调中直接在样式元素上设置变换属性。
标签: javascript html css css-animations css-transforms