如何从 javascript 获取内联块字段集的显示宽度
How to get display width of inline-block fieldset from javascript
如果您有一个带有 display: inline-block 的字段集,它的宽度取决于它包含的元素。您可以看到它,但假设:
<fieldset id='fs' style='display: inline-block'>
<input type=number>
</fieldset>
<script>
var fs=document.getElementById("fs");
console.log("fs.width:",fs.width);
</script>
唯一的输出将是:
fs.width: undefined
在尝试了很多东西之后,我终于能够像这样得到它:
<script>
var fs=document.getElementById("fs");
var fsrects=fs.getClientRects();
var fswidth=fsrects[0].right-fsrects[0].left;
console.log("fswidth:",fswidth);
</script>
然后输出是
fswidth: 98.6640625
一定有更简单的方法!求助!!!
您可能正在寻找 offsetWidth。
The HTMLElement.offsetWidth read-only property returns the layout width of an element. Typically, an element's offsetWidth is a measurement which includes the element borders, the element horizontal padding, the element vertical scrollbar (if present, if rendered) and the element CSS width.
var fs=document.getElementById("fs");
console.log("fs.width:",fs.offsetWidth);
<fieldset id='fs' style='display: inline-block'>
<input type=number>
</fieldset>
如果您有一个带有 display: inline-block 的字段集,它的宽度取决于它包含的元素。您可以看到它,但假设:
<fieldset id='fs' style='display: inline-block'>
<input type=number>
</fieldset>
<script>
var fs=document.getElementById("fs");
console.log("fs.width:",fs.width);
</script>
唯一的输出将是:
fs.width: undefined
在尝试了很多东西之后,我终于能够像这样得到它:
<script>
var fs=document.getElementById("fs");
var fsrects=fs.getClientRects();
var fswidth=fsrects[0].right-fsrects[0].left;
console.log("fswidth:",fswidth);
</script>
然后输出是
fswidth: 98.6640625
一定有更简单的方法!求助!!!
您可能正在寻找 offsetWidth。
The HTMLElement.offsetWidth read-only property returns the layout width of an element. Typically, an element's offsetWidth is a measurement which includes the element borders, the element horizontal padding, the element vertical scrollbar (if present, if rendered) and the element CSS width.
var fs=document.getElementById("fs");
console.log("fs.width:",fs.offsetWidth);
<fieldset id='fs' style='display: inline-block'>
<input type=number>
</fieldset>