【问题标题】:How to catch current css translate() position in javascript如何在 javascript 中捕获当前 css translate() 位置
【发布时间】:2020-10-23 09:47:39
【问题描述】:

我想通过箭头为屏幕上的元素设置动画。翻译时应立即改变方向。因此,如果元素向右移动并且我在动画的一半中按下向下箭头,它应该直接向下并停止向右移动。但是我怎样才能捕捉到元素的当前 x 位置。 offsetLeft 不起作用。它仍然是相同的原点位置。是否可以捕获动画元素的当前位置?谢谢。

【问题讨论】:

    标签: javascript animation transform translate


    【解决方案1】:

    我认为你需要调用 element.getBoundingClientRect()

    let circle = document.querySelector(".animate");
    let style = window.getComputedStyle(circle);
    
    setInterval(() => {
      let rect = circle.getBoundingClientRect();
      console.log(rect.left)
    }, 1000)
    div {
      height: 100px;
      width: 100px;
      border-radius: 100px;
      background: blue;
    }
    
    .animate {
      animation: animate;
      animation-duration: 3s;
      animation-direction: alternate;
      animation-iteration-count: infinite;
      animation-timing-function: linear;
    }
    
    @keyframes animate {
      from {
        transform: translate(0)
      }
      to {
        transform: translate(calc(100vw - 120px))
      }
    }
    <div class="animate"> </div>

    不知道为什么代码 sn-p 会在 console.log 中呈现整个元素,但在实际脚本中它只会返回值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多