When is Element.getBoundingClientRect guaranteed t

2020-06-21 09:30发布

I am working on some code that uses Element.getBoundingClientRect (gBCR), coupled with inline style updates, to perform calculation. This is not for a general website and I am not concerned or interested in if there are "better CSS ways" of doing this task.

The JavaScript is run synchronously and performs these steps:

  1. The parent's gBCR is fetched
  2. Calculations are performed and;
  3. A child element of the parent has inline CSS styles (eg. size and margins) updated
  4. The parent's gBCR is fetched again

Am I guaranteed that the computed client bounds will reflect the new bounding rectangle of the parent at step 4?

If not guaranteed by a specification, is this "guaranteed" by modern1 browser implementations? If "mostly guaranteed", what notable exceptions are there?

Elements are not being added to or removed from the DOM and the elements being modified are direct children of the parent node; if such restrictions / information is relevant.


1"Modern": UIWebView (iOS 6+), WebView (Android 2+), and the usual Chrome/WebKit, FF, IE9+ suspects - including mobile versions.

2条回答
Summer. ? 凉城
2楼-- · 2020-06-21 10:34

Old question, still the problem puzzled me and in my searches I had tumbled on this question. It might help others.

The best guarantee that I could find to make getBoundingClientRect() work reliably is to force a refresh at the top of the window, calculate the positions, and then go back wherever the user was.

Code would look something like:

  scroll_pos = document.documentElement.scrollTop // save current position
  window.scrollTo(0, 0); // go up

  v_align = parseInt(el.getBoundingClientRect().top) // example of gBCR for vert.alignment
  //... whatever other code you might need
  window.scrollTo(0, scroll_pos); // get back to the starting position

Usually the operation is lightning fast, so the user should not notice it.

查看更多
Deceive 欺骗
3楼-- · 2020-06-21 10:35

I'm just stuck at gBCR unreliability on ios8.4.1/Safari8.0.

Prepare a large div on top of body (gBCR is 0) and scroll to bottom (gBCR is negative). Resize the div into 1x1 then window.scrollY automatically goes 0. gBCR should also be 0 but still stay negative value. With setTimeout, 200ms later, you can confirm the right value 0.

查看更多
登录 后发表回答