按钮文本更改时保持按钮大小稳定

Keep size of button stable when button text changes

我有一个 bootstrap 按钮:

<div class="float-right" >
    <label>show as </label>
    <input class="btn btn-outline-primary rounded active" type="button" value="percentage" onclick="toggle(this)" />
</div>

我使用以下方式切换文本:

<script type="text/javascript">
    function toggle(button) {
        if(button.value=="percentage") {
            button.value="units";
        } else {
            button.value="percentage";
        }
    }
</script>

当文本从较长的单词 percentage 更改为较短的单词 units 时,如何让按钮 不调整大小 。即我希望按钮保持与文本 percentage.

相同的大小

请注意,我不想使用 style="min-width: 120px;".

对大小进行硬编码

我建议使用 javascript

选项之一:

<div class="float-right" >
    <label>show as </label>
    <input class="btn btn-outline-primary rounded active" type="button" value="percentage" onclick="toggle(this)" />
</div>
<script type="text/javascript">
    function toggle(button) {
        const buttonWidth = button.offsetWidth;
        if(button.value=="percentage") {
            button.value="units";
            button.style.width = `${buttonWidth}px`;
        } else {
            button.value="percentage";
        }
    }
</script>