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

如何停止CSS transition过渡并保留当前translateY位移值

解决transition运行中停止并保留当前transform状态的方法

核心原理是通过window.getComputedStyle()读取元素实时渲染后的样式值,直接覆盖行内样式即可锁死当前状态,不需要重置transform属性。

最简实现方案

不需要解析transform值,直接读取计算后的属性赋值即可:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <!--mobile friendly-->
  <meta name="viewport" content="width=device-width, user-scalable=yes">
  <style>
    .it {
      width: 300px;
      height: 300px;
      background-color: pink;
      transition: transform 1s cubic-bezier(0.19, 1, 0.22, 1) 0s;
    }
  </style>
</head>
<body>
<div class="it">
</div>

<script type="module">
  const it = document.querySelector(".it")
  setTimeout(() => {
    it.style.transform = "translateY(500px)"
  }, 100)

  setTimeout(() => {
    // 读取当前实时渲染的transform值
    const currentTransform = getComputedStyle(it).transform
    // 临时关闭过渡,避免赋值时触发多余动画
    it.style.transition = 'none'
    // 直接覆盖行内transform,锁死当前状态
    it.style.transform = currentTransform
    // 下一帧恢复过渡配置,不影响后续动画操作
    requestAnimationFrame(() => {
      it.style.transition = ''
    })
  }, 1000)
</script>
</body>
</html>

单独获取当前translateY数值的方法

如果需要单独拿到translateY的数值做其他逻辑处理,可以解析transform的矩阵值:

function getCurrentTranslateY(el) {
  const transform = getComputedStyle(el).transform
  if (transform === 'none') return 0
  const matrixArr = transform.match(/matrix.*\((.+)\)/)[1].split(', ').map(Number)
  // 2d矩阵长度为6,第6位是translateY;3d矩阵长度为16,第14位是translateY
  return matrixArr.length === 6 ? matrixArr[5] : matrixArr[13]
}

// 调用示例
const currentY = getCurrentTranslateY(it)
console.log('当前translateY值:', currentY)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:36:02