Her*_*son 5 html javascript position translate3d
在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();Run Code Online (Sandbox Code Playgroud)
#box{
width:30px; height:30px; background:red;
animation: animX 3s infinite alternate;
}
@keyframes animX { to{ transform:translateX(300px); }}Run Code Online (Sandbox Code Playgroud)
<div id="printer"></div>
<div id="box"></div>Run Code Online (Sandbox Code Playgroud)