为什么getBoundingClientRect只能在本地工作?

时间:2014-12-16 16:37:36

标签: javascript jquery html css bounding-box

考虑以下HTML(JSFiddle link):

<div id="a" class="box">cat</div>
<div id="b" class="box rotate">cat</div>
<div id="c" class="box"><div class="rotate">cat</div></div>

和CSS:

.box    { font-size:500%; }
.rotate { transform: rotate(-90deg); }

使用id=a

测量元素.getBoundingClientRect()的宽度和高度
$(a)[0].getBoundingClientRect().width
$(a)[0].getBoundingClientRect().height

给出(320,91)的维度。在元素id=b上测量相同的内容会给出转置尺寸(91,320)。精彩。

但是,当我尝试测量元素id=c时,它只是将旋转嵌入内部div中,我得到原始尺寸(320,91)!我不应该bc的边界框相同吗?

如果没有,我怎样才能让c的边界框正确报告?


如果相关,我使用的是Chromium,版本37.0.2062.120 Ubuntu 12.04(281580)(64位)。

1 个答案:

答案 0 :(得分:4)

不,c内的旋转位延伸出c,而不会改变其大小。这应该让它更清晰:

&#13;
&#13;
var bbox_a = document.getElementById("a").getBoundingClientRect();
snippet.log("a: " + bbox_a.width + "x" + bbox_a.height);

var bbox_b = document.getElementById("b").getBoundingClientRect();
snippet.log("b: " + bbox_b.width + "x" + bbox_b.height);

var bbox_c = document.getElementById("c").getBoundingClientRect();
snippet.log("c: " + bbox_c.width + "x" + bbox_c.height);
&#13;
.box {
    font-size:500%;
}
.rotate {
    transform: rotate(-90deg);
}
#a {
    border: 1px solid black;
}
#b {
    border: 1px solid red;
}
#c {
    border: 1px solid green;
}
#c .rotate {
    border: 2px solid yellow;
}
&#13;
<div id="a" class="box">cat</div>
<div id="b" class="box rotate">cat</div>
<div id="c" class="box">
    <div class="rotate">cat</div>
</div>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
&#13;
&#13;
&#13;

(我删除了对上面的自动全局变量abc的依赖。这让我依赖自动全局变量而感到紧张,他们还是很容易被遮蔽。)

顺便说一句,您可以使用Chromium的开发工具直观地显示这样的内容:右键单击元素并选择&#34; Inspect element&#34;,然后它将打开开发中的Elements面板工具。此时,当光标位于“元素”面板中元素的标记上时,开发工具将在页面上突出显示该元素(包括其边界框)。

相关问题