在 Javascript 中,当我通过 translate3d 方法使用 gpu 移动元素时,元素样式左位置根本没有改变。由于 CPU 甚至不知道发生了任何运动。
在通过 translate3d 移动元素后,如何跟踪元素的新位置?
最佳答案
使用Element.getBoundingClientRect()
获取元素坐标
这只是一个从 CSS3 翻译(动画)元素中检索 .left
Rect 属性的小示例:
const box = document.getElementById('box');
const printer = document.getElementById('printer');
const printBoxRectLeft = () => {
printer.textContent = box.getBoundingClientRect().left;
requestAnimationFrame(printBoxRectLeft);
};
printBoxRectLeft();
#box{
width:30px; height:30px; background:red;
animation: animX 3s infinite alternate;
}
@keyframes animX { to{ transform:translateX(300px); }}
<div id="printer"></div>
<div id="box"></div>
关于javascript - translate3d后获取div位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28295670/