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

如何实现点击按钮使区块上移并停留在margin-top:-25px位置?

解决动画结束后区块回到初始位置的问题

你的问题出在CSS动画的默认行为上——动画执行完毕后会自动回到初始状态。以下是两种简单的修改方案:

方案一:让动画保持最终状态

给.animation类添加animation-fill-mode: forwards属性,这个属性会强制元素在动画结束后停留在动画的最后一帧状态:

修改后的CSS代码:

.block {
  width: 100px;
  height: 100px;
  background: green;
}

.animation {
  animation: up 750ms forwards; /* 添加forwards属性 */
}

@keyframes up {
  0% {
    margin-top: 0px;
  }
  100% {
    margin-top: -25px;
  }
}

JavaScript和HTML代码无需改动,点击按钮后区块会稳定停在margin-top: -25px的位置。

方案二:用CSS过渡替代关键帧动画

如果不需要复杂的动画路径,直接用transition实现过渡效果更简洁,而且天然会停在目标状态:

修改后的代码:

.block {
  width: 100px;
  height: 100px;
  background: green;
  transition: margin-top 750ms; /* 添加过渡属性 */
}

.block.moved {
  margin-top: -25px; /* 直接定义最终位置 */
}
$('button').click(function() {
  $('.block').addClass('moved');
})

HTML代码保持不变,这种方式逻辑更直观,也从根源上避免了动画复位的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 00:05:19