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

Bootstrap使用input-group-append时输入框聚焦按钮隐藏如何解决

问题原因
  • 核心原因是Bootstrap默认给.form-control元素的:focus状态设置了z-index: 3,你给.input-group-append设置的z-index: 2低于该值,所以输入框聚焦时会覆盖住append元素,视觉上表现为按钮隐藏;输入框失焦时z-index回到默认值1,append元素就会显示出来,和状态更新逻辑无关。
  • 额外问题:绝对定位的append元素会遮挡输入框内的文字,没有预留对应显示空间。
解决方案
  1. 调整.input-group-append的z-index值到4及以上,保证输入框聚焦时也能显示在上层
  2. 给输入框添加右侧内边距,避免输入内容被append元素遮挡
  3. 确认onChange逻辑仅根据输入框内容长度判断showAppend的值,不要绑定聚焦/失焦事件

修正后的完整代码如下:

// onChange逻辑参考,保证输入时实时更新显示状态
const onChange = (e) => {
  const inputValue = e.target.value
  // 只要输入内容非空就显示append按钮
  setShowAppend(inputValue.trim().length > 0)
  // 其他处理输入值的业务逻辑
}

// 组件渲染代码
<div className="input-group" style={{ position: "relative" }}>
  <input
    type="text"
    className="form-control"
    placeholder="Recipient's username"
    aria-label="Recipient's username"
    aria-describedby="basic-addon2"
    onChange={onChange}
    style={{ paddingRight: "100px" }} // 新增:预留右侧append元素的显示空间
  />
  {showAppend === true && (
    <div
      className="input-group-append"
      style={{ position: "absolute", right: 0, zIndex: 4 }} // 调整z-index到4
    >
      <span className="input-group-text" id="basic-addon2">
        @example.com
      </span>
    </div>
  )}
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 00:45:05