[英]Changing the background color of the span and ul when the element is brought into focus?
[英]Is there some way to change color of a label when the input which is a child element in sibling div is brought in focus?
<form>
<label>Hello there</label>
<div>
<input/>
</div>
</form>
当 div 内的输入成为焦点时,有什么方法可以设置 label 的样式。 请在不使用 jQuery 的情况下为 React 或 HTML 提供建议。 例如,当输入成为焦点时,label 的颜色会发生变化。
你可以试试label:focus-within { color: red; }
label:focus-within { color: red; }
。
只要 label 的任何孩子有焦点,这将设置样式。
你可以在这里阅读更多关于它的信息: https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within
您可以使用以下代码:
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>
);
}
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>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.