Get divs position after translate3d

安稳与你 提交于 2019-12-04 12:26:11

问题


In Javascript, when I move an element using the gpu via the translate3d method, the elements style-left position doesnt change at all. As the cpu isnt even aware any motion has occurred.

How do I track what the new position of an element is, after moving it via translate3d?


回答1:


Use Element.getBoundingClientRect() to get the element coordinates

Here's just a small example that retrieves the .left Rect property from a CSS3 translated (animated) element:

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>



回答2:


The style attribute left is set to auto if you do not set it manually. But you should be able to use the jquery function position().

    var position = $('#element').position();
    var left = position.left;

http://jsfiddle.net/nqab2aw7/2/




回答3:


The other answers that use getBoundingClientRect work, but if you want to get the actual numeric values from a translate3d string, use a RegExp:

var xyzArray;
let translate3dValue = 'translate3d(256px, 512px, 0px)';
xyzArray = translate3dValue.replace(/translate3d|px|\(|\)/gi, '').split(',');


来源:https://stackoverflow.com/questions/28295670/get-divs-position-after-translate3d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!