【问题标题】:How to find the size of an element in the document如何在文档中查找元素的大小
【发布时间】:2015-12-28 08:14:11
【问题描述】:

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 的执行似乎在调用 attach() 时的队列中,因此可以使用 Future() 创建一个根据父节点大小调整自身大小的组件。
希望 Future() 保持可靠。

另一个答案

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

异步操作:插入、追加和删除操作是 在某些情况下为了性能而懒惰地进行交易。为了 询问 DOM(例如 offsetHeight、getComputedStyle 等) 在这些操作之一之后立即调用 PolymerDom.flush() 首先。

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

【问题讨论】:

  • 您可以回答自己的问题,也可以将其设为可接受的答案(经过一段时间的延迟)。
  • 感谢您让我知道这一点,也非常感谢您的回答。
  • 问题是,虽然“PolymerDom.flush()”是一个更适合我的问题的单独答案,但这并不总是足够的,因为组件是在 main() 执行之前初始化的(嗯,你肯定知道那)。所以调用 flush 一个真正的答案可能是错误的,因为它只是答案的一半:稍后添加的元素可能会改变组件的大小等。

标签: dart dart-polymer


【解决方案1】:

对此没有标准事件。通常它的工作原理是只为下一个事件循环安排你的代码,以允许 Polymer 通过将你的代码包装在

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-01
    • 2020-11-18
    • 2015-08-22
    • 1970-01-01
    • 2016-04-14
    • 2020-05-08
    • 2015-05-03
    • 2018-08-04
    相关资源
    最近更新 更多