Get position divs after translate3d

In Javascript, when I move an element using gpu using the translate3d method, the style position in the left position does not change at all. Since the CPU does not even know that any movement has occurred.

How can I track what a new position of an element is after moving through translate3d?

+5
source share
3 answers

Use Element.getBoundingClientRect() to get the coordinates of an element

Here is just a small example that extracts the .left Rect property from a translated (animated) CSS3 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> 
+7
source

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

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

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

+3
source

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

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

Source: https://habr.com/ru/post/1212514/


All Articles