alert("Wrong (red): " + document.getElementById("target").getBoundingClientRect().top);
alert("Correct (blue): " + document.getElementById("wrapper").getBoundingClientRect().top);

#target {
transform: translate(20px, -20px) rotateZ(20deg);
background: red;
width: 50px;
height: 50px;
}
#wrapper {
background: blue;
display: inline-block;
}

Text
<div id="wrapper">
<div id="target">
</div>
</div>
further text
&#13;
在上面的示例中,如果没有transform
,则蓝色方块具有确切的位置,红色的 。它还具有红色正方形消耗的空间和位置,作为流入元素。我想用JavaScript获得的位置是蓝色方块的位置。我唯一的问题是,在我的原始代码中,没有#wrapper
,我无法创建一个。那么如何获得可能会或可能不会在该位置上的元素的流入位置(由于transform
,position: relative;
或其他 - 如果有)?
普通的JS或jQuery解决方案都是受欢迎的。但我寻找一个相当简单/简短的解决方案,而不是50多行怪物。
我的尝试:
jQuery('#target').offset()
:考虑transform
(在上例中返回一些负数)。document.getElementById('target').getBoundingClientRect()
:与jQuery&#39; s offset
jQuery('#target').position()
遍历offsetParent
:可能目前有效,但jQuery在这方面的行为被认为是 bug 或根据{{3}}网站(如果我正确地解释该网站),至少会受到即将发生的变化。答案 0 :(得分:0)
使用WebKitCSSMatrix
var node = document.getElementById("target");
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
WebKitCSSMatrix