我在stackoverflow上看到了这两种不同的形式,但解决方案对我不起作用.
基本上,我有一个项目,我将翻译.当我执行obj.style.left或obj.offsetLeft时,在元素被翻译之后,我得到0.无论如何,我可以在用css3翻译后得到元素的坐标/位置吗?
我不能使用jQuery(因为我不能也因为我想了解解决方案,而不仅仅是使用库而不了解下面发生的事情)
有任何想法吗?
非常感谢!
Thi*_*nte 32
你可以使用getBoundingClientRect():
想象一下下面的html块:
<div class="centralizer popup">
<div class="dragger"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
风格:
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;
}
Run Code Online (Sandbox Code Playgroud)
现在您可以使用以下JavaScript来获取正确的位置:
var popup = document.querySelector('.popup');
var rect = popup.getBoundingClientRect();
console.log("popup.getBoundingClientRect(): \n" + "x: " + rect.left + "\ny: " + rect.top);
Run Code Online (Sandbox Code Playgroud)
你可以在jsfiddle中查看结果:
我测试了FF,IE和chrome,它适用于我的所有测试.
met*_*ion 22
好吧,保持紧张因为这不好:
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
});
Run Code Online (Sandbox Code Playgroud)
你可以在这里玩它:
http://jsfiddle.net/duopixel/wzZ5R/