如何查找文档中元素的大小

How to find the size of an element in the document

main()中自定义聚合物元素main-app的offsetHeight为88px。
当在点击处理程序中调用相同的 offsetHeight 方法时,它是 108px。 我猜这是一个时间问题。
当自定义聚合物元素在文档中完全准备好时,是否有任何方法事件让我 运行 回调?

main() async {
  await initPolymer();

  PaperButton pb = querySelector('paper-button');
  MainApp sa = querySelector('main-app');
  if(sa != null){
    print('main-app');
    print(sa.style.width.runtimeType);
    print('offset:' + sa.offset.toString());
    print('offsetHeight:' + sa.offsetHeight.toString());
    print('offsetWidth:' + sa.offsetWidth.toString());
    print('getBoundingClientRect:'+sa.getBoundingClientRect().toString());
    print('contentedge:'+sa.contentEdge.toString());
    print('clientHeight:'+sa.clientHeight.toString());
    print('client:'+sa.client.toString());
    print('marginEdge:'+sa.marginEdge.toString());
  }
  pb.on['tap'].listen((_) {
    print('Button tapped!');
    print('offsetHeight:' + sa.offsetHeight.toString());
  });
}

输出:

main-app
String
offset:Rectangle (8, 8) 643 x 88
offsetHeight:88
offsetWidth:643
getBoundingClientRect:Rectangle (8.0, 8.0) 642.6666870117188 x 88.0
contentedge:Rectangle (8.0, 8.0) 643 x 88
clientHeight:88
client:Rectangle (0, 0) 643 x 88
marginEdge:Rectangle (8.0, 8.0) 643 x 88
index.html:6095 Button tapped!
index.html:6095 offsetHeight:108

编辑: Günter Zöchbauer 的新 Future((){}) 有效,尽管它很老套。
另一个不幸的发现是子节点的初始化发生在设置父节点大小之前。 在我的组件中:

attached() {
    super.attached();
    print('main-app parent offset in attached:'+parent.offset.toString());
  }

主线:

print('main-app');
pb.on['tap'].listen((_) {
    print('Button tapped!');
    print('main-app parent offset:'+ sa.parent.offset.toString());
  });

输出(分别):

main-app parent offset in attached:Rectangle (0, 0) 643 x 246
main-app
Button tapped!
main-app parent offset:Rectangle (0, 0) 643 x 334

幸运的是,main 的执行似乎在调用 attached() 时在队列中,因此可以使用 Future() 创建一个根据父节点大小调整自身大小的组件。
希望 Future() 保持可靠。

另一个答案

终于找到了!! https://github.com/dart-lang/polymer-dart/wiki/local-dom

Async operations: The insert, append, and remove operations are transacted lazily in certain cases for performance. In order to interrogate the DOM (e.g. offsetHeight, getComputedStyle, etc.) immediately after one of these operations, call PolymerDom.flush() first.

PolymerDom.flush() 是我需要的。 但是正如我在评论中提到的,Future 仍然应该被使用。

没有这方面的标准事件。通常它的工作原理是为下一个事件循环安排你的代码,让 Polymer 通过将你的代码包装在

中来完成它的工作
new Future((){
  // your code here 
} );`

如果它是您自己的组件,您可以在 attached() 中自己触发一个事件,但要确保触发事件的代码也应该在未来包装(例如模板 if/for 可能不会在 attached())

内完成