首页 > 解决方案 > 按钮文本更改时保持按钮大小稳定

问题描述

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

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

注意我宁愿不使用硬编码大小style="min-width: 120px;"

标签: htmlcsstwitter-bootstrapbuttonresize

解决方案


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


推荐阅读