简体   繁体   English

在translate3d之后获得div位置

[英]Get divs position after translate3d

In Javascript, when I move an element using the gpu via the translate3d method, the elements style-left position doesnt change at all. 在Javascript中,当我通过translate3d方法使用gpu移动元素时,元素样式左侧位置根本不会改变。 As the cpu isnt even aware any motion has occurred. 因为cpu甚至不知道发生了任何动作。

How do I track what the new position of an element is, after moving it via translate3d? 在通过translate3d移动元素后,如何跟踪元素的新位置?

Use Element.getBoundingClientRect() to get the element coordinates 使用Element.getBoundingClientRect()来获取元素坐标

Here's just a small example that retrieves the .left Rect property from a CSS3 translated (animated) element: 这里只是一个从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> 

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(). 但是你应该能够使用jquery函数position()。

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

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

The other answers that use getBoundingClientRect work, but if you want to get the actual numeric values from a translate3d string, use a RegExp : 使用getBoundingClientRect的其他答案有效,但如果要从translate3d字符串中获取实际数值,请使用RegExp

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM