javascript - 从左到右然后从右到左动画div

标签 javascript animation dom

我正在看这个演讲:https://www.youtube.com/watch?v=cCOL7MC4Pl0

演讲者谈论 JS 任务和 DOM 渲染。他给出了以下示例:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Task</title>

    <style>
      * {
        box-sizing: border-box;
      }

      .box {
        width: 50px;
        height: 50px;
        background-color: pink;
      }
    </style>
  </head>

  <body>
    <div class="box"></div>

    <script>
      var box = document.querySelector(".box");

      box.addEventListener("click", () => {
        box.style.transform = "translateX(500px)";
        box.style.transition = "transform 1s ease-in-out";
        box.style.transform = "translateX(250px)";
      });
    </script>
  </body>
</html>

并尝试使对象(在单击事件上)从位置 0 到位置 500px,然后从 500px 到 250px 设置动画。换句话说,从左到右,从右到中间。

他使用了以下代码:

var box = document.querySelector(".box");
box.addEventListener("click", () => {
  box.style.transform = "translateX(500px)";
  box.style.transition = "transform 1s ease-in-out";
  box.style.transform = "translateX(250px)";
});

然后他解释了为什么它没有按预期工作 - 因为浏览器会在渲染/执行动画之前进行所有计算。这里一切都很好。

但是,他说他通过将最后一个 box.style.transform = "translateX(250px)"; 包装成双(嵌套)requestAnimationFrame()调用。当我尝试这样做时,它做了与以前完全相同的事情。它没有用。这是代码:

box.style.transform = "translateX(500px)";
box.style.transition = "transform 1s ease-in-out";
requestAnimationFrame(() => {
  requestAnimationFrame(() => {
    box.style.transform = "translateX(250px)";
  });
});

我在这里错过了什么?如何让浏览器先对500px进行变换操作,再变换回250px?

最佳答案

视频中有错误。

这是正确的代码:

box.addEventListener("click", () => {
  box.style.transform = "translateX(500px)";

  requestAnimationFrame(() => {
    requestAnimationFrame(() => {
      box.style.transition = "transform 1s ease-in-out";
      box.style.transform = "translateX(250px)";
    });
  });
});

关于javascript - 从左到右然后从右到左动画div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58145264/

相关文章:

wpf - wpf 中最简单的按钮位置动画是什么?

javascript - RegEx - 删除最后一个下划线和扩展名之间的所有内容

javascript - jquery - 将for循环生成的图标 append 到列表项 anchor 中

javascript - d3js 防止拖拽点击事件

javascript - Raphael JS 路径的“删除”动画

Qt Quick TreeView 展开/折叠的动画

javascript - Dialogflow 不显示访问 token

javascript - JavaScript 对象的表单输入

javascript - 检查对象是否是文本框 - javascript

javascript - 我如何告诉 javascript 立即更新 DOM?