当作为同级div中的子元素的输入成为焦点时,有没有办法改变标签的颜色


<form>
<label>Hello there</label>
<div>
<input/>
</div>
</form>

当div内部的输入被聚焦时,我们有没有办法对标签进行样式设置。请给出在不使用jQuery的情况下使用React或HTML的建议。例如,当输入聚焦时,标签的颜色会发生变化。

您可以尝试label:focus-within { color: red; }

每当它的任何子项有焦点时,这将为标签设置样式。

您可以在此处阅读更多信息:https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-内

import * as React from 'react';
export default function App() {
const [Color, setColor] = React.useState('#e31f1f');
const newColor = '#1fe3b2';
const OldColor = '#e31f1f';
const changeCollorFunction = (color: string) => {
setColor(color);
};
return (
<div>
<form>
<label
id="change-color"
style={{
color: Color,
}}
>
Hello there
</label>
<div>
<input
type="text"
onFocus={() => {
changeCollorFunction(newColor);
}}
onBlur={() => {
changeCollorFunction(OldColor);
}}
/>
</div>
</form>
</div>
);
}

您可以使用以下代码:

export default function App() {
const [focuse,setFocuse]=useState(false);
return (
<div className="App">
<label style={{backgroundColor:focuse?'red':'transparent'}}>Hello there</label>
<div>
<input onFocus={()=>setFocuse(true)}/>
</div>
</div>
);
}

相关内容

最新更新