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

如何在React/HTML中实现兄弟Div内Input获焦时改变Label颜色?

解决方案

一、纯HTML+CSS实现

不用写JS,靠CSS选择器就能直接实现,两种方案任选:

方案1:利用:focus-within选择器

:focus-within会选中包含聚焦元素的父容器,我们可以借助它定位到目标label:

/* 当form内的input聚焦时,选中同级的label */
form:focus-within > label {
  color: #ff4444;
}

方案2:利用:has选择器(更精准)

:has能检测父元素是否包含满足条件的子元素,可精准定位到div内input聚焦的场景:

/* 仅当div里的input聚焦时,修改label颜色 */
form:has(> div input:focus) > label {
  color: #ff4444;
}

注::has选择器目前已被Chrome、Firefox等主流浏览器支持。

二、React环境实现

通过React状态管理来控制样式,步骤清晰:

  1. 定义状态变量记录input是否聚焦;
  2. 给input绑定onFocus和onBlur事件切换状态;
  3. 根据状态给label设置对应样式。

示例1:行内样式写法

import { useState } from 'react';

function MyForm() {
  const [isInputFocused, setIsInputFocused] = useState(false);

  return (
    <form>
      <label style={{ color: isInputFocused ? '#ff4444' : 'inherit' }}>
        Hello there
      </label>
      <div>
        <input
          onFocus={() => setIsInputFocused(true)}
          onBlur={() => setIsInputFocused(false)}
        />
      </div>
    </form>
  );
}

示例2:CSS类名写法(更灵活)

import { useState } from 'react';
import './MyForm.css';

function MyForm() {
  const [isInputFocused, setIsInputFocused] = useState(false);

  return (
    <form>
      <label className={isInputFocused ? 'focused-label' : ''}>
        Hello there
      </label>
      <div>
        <input
          onFocus={() => setIsInputFocused(true)}
          onBlur={() => setIsInputFocused(false)}
        />
      </div>
    </form>
  );
}

对应的MyForm.css:

.focused-label {
  color: #ff4444;
  font-weight: bold; /* 可按需添加更多样式 */
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 16:03:37