css平移如何中途暂停

img


我想知道css的平移动画如何暂停呢?我百度看说用

animation-play-state:paused;

的,但是我这个平移是动态的,没有办法写在@keyframes里啊
我现在是在暂停的事件中获取下降的距离然后取消元素的平移属性,再把下降的距离赋给元素,但是这样会有一个问题就是当设备的运算处理能力不足时会看到一个明显的上拉动作(这里的上拉我知道是因为取消平移效果后元素会回到原来的位置,然后又赋值了新的距离,所以在运算能力不足的设备上这个上拉效果尤为明显)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    #box {
      top: 100px;
      position: fixed;
      width: 100px;
      height: 100px;
      background: red;
      animation: move 3s linear 0s infinite alternate;
    }
    
    .stop {
      animation-play-state: paused !important;
    }
    
    @keyframes move {
      from {
        left: 0;
      }
      to {
        left: calc(100% - 100px);
      }
    }
  </style>
</head>
<body>
<button id="btn">change animation</button>
<div id="box"></div>
<script>
  const box = document.getElementById('box')
  document.getElementById('btn').addEventListener('click', function () {
    if (box.classList.contains('stop')) {
      box.classList.remove('stop')
    } else {
      box.classList.add('stop')
    }
  })
</script>
</body>
</html>

用js加上这属性,这个属性也可以写在css类名里面


xxx.style.animationPlayState = "paused"

或者考虑在js中设置动画实现平移效果呢:
https://www.cnblogs.com/dj-chen/p/4286855.html
这样就能达到平移且中途暂停的效果了