You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ember.js按钮切换文本时如何固定宽度适配最长字符串?

解决按钮切换文本时的布局抖动问题

单个按钮可显示文本“Show”或“Hide”,切换时按钮宽度会变化,需求是让按钮始终占用最长文本所需的最小宽度,避免页面布局抖动。

原代码

<div ...attributes>
{{#let (unique-id) as |passwordId|}}
<label class="block uppercase" for="{{passwordId}}">password</label>
<div class="flex flex-row">
    <div class="border-2 border-besler-blue p-2">
        <input class="outline-none" id="{{passwordId}}" type="{{if this.isHidden "password" "text"}}" value="{{@startValue}}" placeholder="{{@placeholder}}">
    </div>
    <div class="border-r-2 border-y-2 border-besler-blue p-2 bg-gray-200">
        <button type="button" {{on "click" this.toggleShow}}>{{if this.isHidden "Show" "Hide"}}</button>
    </div>
</div>
{{/let}}
</div>

优化后的代码

<div ...attributes>
    {{#let (unique-id) as |passwordId|}}
    <label class="block uppercase" for="{{passwordId}}">password</label>
    <div class="flex flex-row">
        <div class="border-2 border-besler-blue p-2">
            <input class="outline-none" id="{{passwordId}}" type="{{if this.isHidden " password" "text" }}"
                value="{{@startValue}}" placeholder="{{@placeholder}}">
        </div>
        <button class="border-r-2 border-y-2 border-besler-blue p-2 bg-gray-200 text-center" type="button"
            {{on "click" this.toggleShow}}>
            <div>
                <span class="absolute {{if this.isHidden " opacity-0"}}">Hide</span>
                <span class="{{if (not this.isHidden) " opacity-0"}}">Show</span>
            </div>
        </button>
    </div>
    {{/let}}
</div>

实现说明

  • 同时在按钮内渲染“Show”和“Hide”两个文本元素,通过opacity-0类控制元素的显示/隐藏状态,按钮会自动适配较长文本(“Hide”)的宽度,彻底避免切换时的布局抖动。
  • 需将最长文本放在第二个元素位置,无需额外设置position: relative。

内容的提问来源于stack exchange,提问作者Display name

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 08:12:38