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

如何在表单input获取焦点时更改对应label的文本颜色

问题根因

你使用的+相邻兄弟选择器只能匹配紧跟在当前元素之后的同级元素,但你的HTML结构里label放在input前面,所以input:focus + label无法选中对应label,样式不生效。


解决方案

方案1:用父元素:focus-within伪类(无需修改HTML,最便捷)

仅修改CSS即可适配现有结构:

input {
  background: transparent;
  position: relative;
}

label {
  color: black;
}

/* 父容器内input聚焦时,选中容器内的label */
.input-box:focus-within label {
  color: red !important;
}

/* 如果需要input聚焦时加边框,可以加下面这段 */
.input-box:focus-within input {
  border: 1px solid white;
  outline: none;
}

你现有的HTML代码不需要做任何调整就能生效。

方案2:调整HTML元素顺序适配原有选择器

如果要保留你原来写的input:focus + label选择器,可以调整HTML里元素的顺序,再用flex的order属性调整视觉显示顺序:

<div class="input-box d-flex flex-column">
  <input class="py-2 border-0 text-white" id="name" type="text" />
  <!-- order:-1 让label视觉上显示在input前面 -->
  <label for="name" class="py-2" style="order: -1;">Your Name</label>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:36:04