如何从元素的脚本中获取自定义元素的宽度?
<polymer-element name="his-elem">
<div>
blah
</div>
</polymer-element>
@CustomTag('his-elem')
class blah extends PolymerElement {
@override
void attached() {
// how do I get the <his-elem>'s width (just width, no padding border stuff) here?
// document.querySelector('his-elem').getComputedStyle().width gives me "auto"...
}
}
更新
添加
:host {display: block;}
到his-element,那么你可以通过<his-elem>.clientWidth
得到实际宽度.
最佳答案
当其他方法不起作用时,我会使用它:
this.getBoundingClientRect().width
另见 https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect
**在聚合物中 <= 0.16
您需要调用
super.attached()
之前 @override
void attached() {
super.attached();
print(this.getBoundingClientRect().width);
// or
print(this.getComputedStyle().width);
}
在调用
super.attached()
之前该元素尚未附加到 DOM 并且不会返回正确的宽度。实际上与覆盖 attached
不调用 super.attached()
在您阻止附加的方法内。
关于dart - 获取在 Dart 中使用 <polymer-element> 创建的自定义元素的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27602508/