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
在上面的例子中,蓝色方 block 有准确的位置,如果没有 transform
,红色方 block 会有。它也恰好具有红色方 block 占用的空间和位置,作为流入元素。我想在 JavaScript 中获取的位置是蓝色方 block 的位置。我唯一的问题是,在我的原始代码中,没有 #wrapper
并且我无法创建一个。那么我如何获得可能位于或不位于该位置的元素的流入位置(由于 transform
、position: relative;
或其他 - 如果有是)?
欢迎使用纯 JS 或 jQuery 解决方案。但我正在寻找一个相当简单/简短的解决方案,而不是一些 50 多行的怪物。
我的尝试:
jQuery('#target').offset()
:将transform
考虑在内(在上例中返回一些负数)。document.getElementById('target').getBoundingClientRect()
:与 jQuery 的offset
相同jQuery('#target').position()
遍历offsetParent
:可能 目前有效,但 jQuery 在这方面的行为根据 this,被认为是一个错误,或者至少会受到即将发生的变化的影响站点(如果我正确解释该站点)。
最佳答案
使用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
浏览器兼容性:
- 检查this answer了解如何处理不支持
WebKitCSSMatrix
的浏览器
关于javascript - 获取 DOM 元素流入位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38727611/