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

4

我有一个 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>

如何使按钮在将文本从较长的单词“百分比”更改为较短的单词“单位”时不重新调整大小。即,我希望按钮保持与其具有文本“百分比”时相同的大小。
请注意,我不想使用style="min-width: 120px;"来硬编码大小。

相关:https://stackoverflow.com/a/55328972/8620333(如果您能够使用“button”而不是“input”) - Temani Afif
1个回答

4
我建议使用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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接