如何在 JavaScript 中进行 css3 翻译后获取元素的位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4975727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the position of an element after css3 translation in JavaScript?
提问by ant
I saw this posted in 2 different forms on stackoverflow, but the solutions don't work for me.
我在 stackoverflow 上看到了以 2 种不同形式发布的这篇文章,但这些解决方案对我不起作用。
Essentially, I have an item that I will translate. When I do a obj.style.left or obj.offsetLeft, after the element has been translated, I get 0. Is there anyway I can get the coordinates/position of an element after it has been translated with css3?
基本上,我有一个项目要翻译。当我执行 obj.style.left 或 obj.offsetLeft 时,在元素被翻译后,我得到 0。无论如何,我可以在用 css3 翻译后获得元素的坐标/位置吗?
I can't use jQuery (because I can't and also because I want to understand the solution, not just use the library without understanding what is happening underneath)
我不能使用 jQuery(因为我不能,也因为我想了解解决方案,而不仅仅是在不了解下面发生的事情的情况下使用库)
Any ideas?
有任何想法吗?
Thanks much!
非常感谢!
回答by Thiago Bustamante
You can use getBoundingClientRect()
:
您可以使用getBoundingClientRect()
:
Imagine the following html block:
想象一下下面的 html 块:
<div class="centralizer popup">
<div class="dragger"></div>
</div>
And the style:
和风格:
body {
background:#ccc;
}
.centralizer {
position:absolute;
top:150px;
left:170px;
width:352px;
height:180px;
overflow:auto;
-webkit-transform: translateY(-50%) translateX(-50%);
-moz-transform: translateY(-50%) translateX(-50%);
-ms-transform: translateY(-50%) translateX(-50%);
transform: translateY(-50%) translateX(-50%);
}
.popup {
background:white;
box-shadow:0 0 0 2px rgba(0, 0, 0, 0.1), 0 0 15px rgba(0, 0, 0, 0.3);
border-radius:3px;
}
.dragger {
background:#eee;
height:35px;
border-radius:3px 3px 0 0;
border-bottom:1px solid #ccc;
}
Now you can use the following javascript to get the correct position:
现在您可以使用以下 javascript 来获得正确的位置:
var popup = document.querySelector('.popup');
var rect = popup.getBoundingClientRect();
console.log("popup.getBoundingClientRect(): \n" + "x: " + rect.left + "\ny: " + rect.top);
You can check the result in the jsfiddle:
您可以在jsfiddle 中检查结果:
I tested on FF, IE and chrome, and it worked on all my tests.
我在 FF、IE 和 chrome 上进行了测试,它适用于我的所有测试。
回答by methodofaction
Ok, hold tight because this is not nice:
好吧,坚持住,因为这不好:
window.addEventListener('load', function(){
var node = document.getElementById("yourid");
var curTransform = new WebKitCSSMatrix(window.getComputedStyle(node).webkitTransform);
console.log(node.offsetLeft + curTransform.m41); //real offset left
console.log(node.offsetTop + curTransform.m42); //real offset top
});
You can play with it here:
你可以在这里玩它: