除非我使用css设置,否则element的clientWidth为0 [英] clientWidth of element is 0 unless I set it with css
问题描述
如何在无需设置元素宽度的情况下获得CSS的width属性?如果设置了宽度,它可以工作,但是如果我不设置宽度,即使我在使用调试器进行检查后也看到宽度不是0,但宽度仅为0.
How can I get an elements width without setting it's width property in CSS? If I set the width it works, but if I don't the width is just 0 even though I can see it's not after inspecting with debugger.
let width = this.htmlElement.clientWidth;
HTML
<label [model]="foobar">0</label>
推荐答案
改为使用 offsetWidth
let width = this.htmlElement.offsetWidth;
docs 中的第一行 clientWidth
是
对于没有CSS的元素,
Element.clientWidth
属性为零,或者内联布局框,否则为元素中的内部宽度像素
The
Element.clientWidth
property is zero for elements with no CSS or inline layout boxes, otherwise it's the inner width of an element in pixels
另一方面,offsetWidth是一个只读属性,它返回元素的布局宽度,而不管元素是否以给定的宽度设置样式.
The offsetWidth on the other hand is a read-only property that returns the layout width of an element, regardless of wether or not the element is styled with a given width.
var el = document.getElementById('foobar');
console.log('clientWidth : '+ el.clientWidth );
console.log('offsetWidth : '+ el.offsetWidth );
<label id="foobar">This has width ..................</label>
这篇关于除非我使用css设置,否则element的clientWidth为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!