【问题标题】:Javascript animate Method Accumulation ProblemJavascript animate 方法累积问题
【发布时间】:2021-07-12 09:14:17
【问题描述】:

我正在尝试做一个动画示例,但积累有问题。第一次点击按钮,翻译动画完成,元素的位置永久改变。但是,在第二次单击时,它会再次执行平移动画,但这次不会保留最后一个位置。如何克服这一点?我浏览了 MDN 文档并应用了可选部分,但未能完成此挑战。问候,

https://jsfiddle.net/ja218pbr/19/

document.getElementsByTagName("button")[0].addEventListener("click", function() {
    document.querySelectorAll("div")[0].animate([
  {transform: 'translate(100%, 0)'}
    ], {
    duration: 250,
    composite: "accumulate",
    iterationComposite: "accumulate",
    fill: "forwards"
    });
});

【问题讨论】:

    标签: javascript html css animation


    【解决方案1】:

    如果我的理解正确,您希望能够让对象从之前结束的位置再次滑动。为此,我们可以在每次单击按钮时获取 boundingClientRect 并通过基本上获取对象的宽度并添加客户端矩形的左侧距离来计算新的平移距离,这将有效地允许矩形从距离移动它之前结束了。我还删除了composite 属性,因为它导致矩形跳过正确的位置。

    document.getElementsByTagName("button")[0].addEventListener("click", function() {
      const clientRect = document.querySelectorAll("div")[0].getBoundingClientRect();
      const translationX = clientRect.width + clientRect.left;
      document.querySelectorAll("div")[0].animate([{
        transform: `translate(${translationX}px, 0)`
      }], {
        duration: 250,
        iterationComposite: "accumulate",
        fill: "forwards"
      });
    
    });
    body {
      margin: 0;
    }
    
    div {
      position: relative;
      height: 150px;
      width: 150px;
      background-color: yellow;
      text-align: center;
      line-height: 150px;
    }
    <div>Moving Object</div>
    <button>Press</button>

    【讨论】:

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