【问题标题】:How to calculate the position (x,y) of an element on the page without triggering reflow using Dart (in js)?如何在不使用 Dart(在 js 中)触发重排的情况下计算页面上元素的位置(x,y)?
【发布时间】:2014-05-16 23:40:19
【问题描述】:

我使用 Dart(编译为 JS)计算页面中元素的位置。但是我读到这可能会触发回流,这会导致时间成本高昂吗?这是真的吗?

Reflow/Layout performance for large application

Position offset(Element elem) {
  final docElem = document.documentElement;
  final box = elem.getBoundingClientRect();

  double left = box.left + window.pageXOffset - docElem.clientLeft;
  double top = box.top  + window.pageYOffset - docElem.clientTop;
  int width = box.width.truncate();
  int height = box.height.truncate();
  return new Position(left.truncate(), top.truncate(),
                      width, height);
}

【问题讨论】:

    标签: dart reflow


    【解决方案1】:

    减少回流的关键是批量读写。如果在读取之前发生了挂起的写入,则读取可能会触发回流,但顺序读取不会触发回流。单独来看,很难判断这是否会触发回流。您可以通过首先使用requestAnimationFrame 请求重排来防止它发生。当您有多个读取并希望在所有读取之前仅触发一次回流时,这很有帮助,但它们都必须使用requestAnimationFrame

    在 Dart 中,我们为您提供了一个 animationFrame 属性,该属性返回一个 Future 以更加符合规范。

    棘手的部分是因为animationFramerequrestAnimationFrame 是异步的,所以你的offset 函数必须是to,并返回一个Future<Position>。这必然会导致所有调用者也是异步的。

    Future<Position> offset(Element elem) {
      return window.animationFrame.then((_) {
        final docElem = document.documentElement;
        final box = elem.getBoundingClientRect();
    
        double left = box.left + window.pageXOffset - docElem.clientLeft;
        double top = box.top  + window.pageYOffset - docElem.clientTop;
        int width = box.width.truncate();
        int height = box.height.truncate();
    
        return new Position(left.truncate(), top.truncate(),
                            width, height);
      });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-21
      • 2022-07-10
      相关资源
      最近更新 更多