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

标签 html css twitter-bootstrap button resize

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

关于html - 按钮文本更改时保持按钮大小稳定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57944781/

相关文章:

javascript - 循环音频指定的次数 Html5 或 Javascript

javascript - 预览后打印媒体查询不隐藏类

html - Bootstrap 根据屏幕大小显示行中的元素数

css - 推特 Bootstrap : Getting Form Inputs and Buttons to be same the height in Chrome and Firefox

javascript - 如何使用 ajax 发布表单并返回数组中的数据?

javascript - CSS 两列动态宽度

html - 并排 float 无符号列表中的 2 个元素

html - 电子邮件 HTML 签名在 Web 客户端上添加空白 HTML 元素,导致布局中断

java - javaFX中具有不同大小节点的TreeTableView

java - Bootstrap 追加 div