无需JavaScript,使用CSS实现输入框聚焦时修改标签字体颜色与边框颜色的方法
不用JavaScript实现Input焦点时修改对应Label样式
当然可以!完全不需要借助JavaScript,纯CSS就能搞定这个需求。结合你现有的HTML结构,我们可以利用CSS的:focus-within伪类来实现——这个伪类会在父元素包含的任意子元素获得焦点时触发,刚好能匹配你的场景。
完整实现代码
首先更新你的CSS,添加焦点状态下的样式,还可以加上过渡动画让颜色变化更平滑:
.input-label { display: flex; align-items: center; height: 16px; font-weight: 700; font-size: 11px; letter-spacing: .1px; color: #989898; text-transform: uppercase; transition: color 0.3s ease; /* 可选:添加颜色过渡动画 */ } .form-control{ display: inline-block; max-width: 100%; word-wrap: normal; background: transparent; border: none; border-bottom: 2px solid #cacaca; color: #4a4a4a; font-size: 1.19em; height: 35px; letter-spacing: .2px; padding: 7px 0; width: 100%; resize: none; transition: border-color 0.3s ease; /* 可选:添加边框颜色过渡动画 */ } /* 核心样式:当父元素内的输入框获得焦点时,修改标签和输入框样式 */ .firstname:focus-within .input-label { color: #007bff; /* 替换成你想要的焦点时的标签字体颜色 */ } .firstname:focus-within .form-control { border-bottom-color: #007bff; /* 替换成你想要的焦点时的输入框边框颜色 */ }
你的HTML结构保持不变即可:
<div class="firstname"> <label for="name" class="input-label" id="name-label">First Name</label> <input type="text" class="form-control" id="name" placeholder="First Name" required> </div>
原理说明
:focus-within伪类会在.firstname容器内的任何元素(这里就是你的input)获得焦点时触发。- 一旦触发,我们就可以通过后代选择器选中容器内的
.input-label和.form-control,分别修改它们的字体颜色和边框颜色。 - 加上
transition属性是为了让颜色变化更自然,提升用户体验,如果你不需要动画效果,可以直接去掉这两行。
内容的提问来源于stack exchange,提问作者Fatal Error
相关产品推荐
相关产品推荐

