我现在界面上有一个方块在css的动画下不停的移动,然后我用定时器去监听这个方块的位置,但是我setTimeout的时间间隔都设置为0了还是会有误差,捕获到的位置和实际方块的位置会有偏差,是否有那种无时间间隔的定时器,或者如何才能精确的捕获不停移动的方块的位置
1条回答 默认 最新
- MAXLZ 2022-09-28 16:15关注
可以使用
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>
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录
悬赏问题
- ¥15 请完成下列相关问题!
- ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
- ¥15 求daily translation(DT)偏差订正方法的代码
- ¥15 js调用html页面需要隐藏某个按钮
- ¥15 ads仿真结果在圆图上是怎么读数的
- ¥20 Cotex M3的调试和程序执行方式是什么样的?
- ¥20 java项目连接sqlserver时报ssl相关错误
- ¥15 一道python难题3
- ¥15 牛顿斯科特系数表表示
- ¥15 arduino 步进电机