什么时候Element.getBoundingClientRect保证更新/准确?

时间:2014-11-08 03:43:56

标签: javascript html css reflow getboundingclientrect

我正在研究一些使用Element.getBoundingClientRect(gBCR)和内联样式更新的代码来执行计算。 这不适用于一般网站,如果有“更好的CSS方式”来执行此任务,我并不关心或感兴趣。

JavaScript以同步方式运行并执行以下步骤:

  1. 获取父母的gBCR
  2. 执行计算并且;
  3. 父级的子元素已更新内联CSS样式(例如,大小和边距)
  4. 再次获取父母的gBCR
  5. 我是否保证计算出的客户端边界将在步骤4中反映父级的新边界矩形

    如果规范不能保证,现代 1 浏览器实现“保证”吗?如果“主要是保证”,那么有什么明显的例外?

    元素被添加到DOM或从DOM中删除,被修改的元素是父节点的直接子元素;如果这些限制/信息是相关的。


    1 “现代”:UIWebView(iOS 6+),WebView(Android 2+),以及通常的Chrome / WebKit,FF,IE9 +嫌疑人 - 包括手机版本

2 个答案:

答案 0 :(得分:1)

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.

答案 1 :(得分:0)

老问题,这个问题仍然困扰着我,在搜索中我跌倒了。这可能会帮助其他人。

我能找到使getBoundingClientRect()可靠工作的最好保证是,在窗口顶部强制刷新,计算位置,然后返回用户所在的任何位置。

代码类似于:

  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

通常该操作快如闪电,因此用户不应注意到它。

相关问题