我现在界面上有一个方块在css的动画下不停的移动,然后我用定时器去监听这个方块的位置,但是我setTimeout的时间间隔都设置为0了还是会有误差,捕获到的位置和实际方块的位置会有偏差,是否有那种无时间间隔的定时器,或者如何才能精确的捕获不停移动的方块的位置
可以使用requestAnimationFrame
.
例如下面这个例子,红色box使用CSS animation动画,通过requestAnimationFrame
将box的位置信息复制给line,box和line达到同时移动的效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.box {
position: fixed;
width: 200px;
height: 200px;
background: red;
animation: move 3s infinite 0s linear alternate;
}
.line {
position: fixed;
height: 400px;
width: 5px;
background: green;
}
@keyframes move {
from {
left: 0;
}
to {
left: 200px;
}
}
</style>
</head>
<body>
<div class="box"></div>
<div class="line"></div>
<script>
const box = document.querySelector('.box'),
line = document.querySelector('.line')
function getBoxTransform() {
line.style.left = window.getComputedStyle(box).left
window.requestAnimationFrame(getBoxTransform)
}
window.requestAnimationFrame(getBoxTransform)
</script>
</body>
</html>