我正在看这个演讲: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/