cat

Why does getBoundingClientRect only work locally?

Consider the following 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> 

and CSS:

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

Measuring the width and height of an id=a element using .getBoundingClientRect()

 $(a)[0].getBoundingClientRect().width $(a)[0].getBoundingClientRect().height 

gives the sizes (320,91) . Measuring the same element on the id=b element gives transposed dimensions (91,320) . Wonderful.

However, when I try to measure the id=c element, which simply nests the rotation inside the inner div, I get the initial dimensions (320,91) ! Are the bounding boxes for b and c not the same?

If not, how can I get the bounding box c for the report correctly?


If appropriate, I use Chromium, version 37.0.2062.120 Ubuntu 12.04 (281580) (64-bit).

+5
source share
1 answer

No, the rotated bit inside c comes out of c without changing its size. This should make it a little clearer:

 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); 
 .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; } 
 <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.imtqy.com/simple-snippets-console/snippet.js"></script> 

(I removed the dependency on automatic global bindings a , b and c above. It just makes me nervous to rely on automatic global variables, they are so easily obscured.)

BTW, you can visualize things like this using the Chromium dev tools: right-click on an element and select "Inspect element" and it will open the "Elements" panel in dev tools. At this point, when your cursor is over the markup for an element in the Element panel, dev tools will highlight that element (including its bounding box) on the page.

+4
source

Source: https://habr.com/ru/post/1209254/


All Articles