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

表单内输入框获得焦点时如何修改对应label标签的文字颜色

原CSS失效原因

CSS选择器默认从左到右匹配后代元素,你写的.tag-field input.tag-input:focus label逻辑是「选中获得焦点的.tag-input内部的label元素」,但你的DOM结构中label是input的祖先元素,CSS没有原生的「子元素触发选中父元素」的普通选择器,因此规则无法生效。


方案1:CSS :focus-within 实现(无需修改现有HTML,优先推荐)

:focus-within 伪类会在元素本身或其任意后代元素获得焦点时触发匹配,正好适配你的嵌套结构,直接添加如下CSS即可:

.tag-field label:focus-within {
  color: red;
}

注:该特性兼容除IE外的所有主流现代浏览器


方案2:JS实现(兼容全浏览器,无需修改HTML)

如果需要兼容IE等老旧浏览器,可以通过JS绑定焦点事件实现:

  1. 添加JS逻辑:
document.querySelectorAll('.tag-field .tag-input').forEach(input => {
  const targetLabel = input.closest('label')
  input.addEventListener('focus', () => targetLabel.classList.add('label-focused'))
  input.addEventListener('blur', () => targetLabel.classList.remove('label-focused'))
})
  1. 配套CSS:
.tag-field label.label-focused {
  color: red;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 00:06:03