You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用@keyframes为div添加下移200px后再上移的动画?

实现div先下移200px再复位的动画效果

你可以通过在动态创建的样式中添加@keyframes规则,并给目标元素绑定动画属性来实现需求。这里用transform: translateY()实现位移,比修改margin更流畅高效。

修改后的JavaScript代码

var style = document.createElement('style');
style.type = 'text/css';
// 新增@keyframes动画规则 + 保留原有元素样式
style.innerHTML = `
@keyframes moveDownUp {
  0% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(200px); /* 下移200px */
  }
  100% {
    transform: translateY(0); /* 回到初始位置 */
  }
}
.moveUp{
  background-color:red; 
  width:40px;
  height:40px;
  margin:auto;
  margin-top:3em;
  animation: moveDownUp 2s ease; /* 绑定动画:名称、时长、缓动函数 */
}
`;
document.getElementsByTagName('head')[0].appendChild(style);

对应的HTML(无需修改)

<body>
  <div class="moveUp"></div>
  <script src="script.js"></script>
</body>

关键说明

  • @keyframes moveDownUp:定义动画的三个关键帧,0%为初始状态,50%完成下移动作,100%回归原位
  • animation属性:指定动画名称moveDownUp、时长2秒,ease是默认缓动效果(可替换为linear等其他值)
  • 若需要动画循环播放,给animation添加infinite参数即可,示例:animation: moveDownUp 2s ease infinite;

内容的提问来源于stack exchange,提问作者Teeee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 19:48:45