我想在输入焦点上着色标签的效果。就像我对焦输入框一样,标签颜色应该变为蓝色。但这不起作用,我想知道为什么以及如何解决这个问题?
.test-label{
color: purple;
}
.test-box:focus .test-label{
color: blue !important;
}

<form>
<label class = "test-label">Label</label>
<br />
<input type = "text" class = "test-box">
</form>
&#13;
答案 0 :(得分:2)
您可以使用focus-within
。
import { LoginScreen } from Paths
.test-label {
color: purple;
}
form:focus-within .test-label {
color: blue;
}
答案 1 :(得分:2)
将input
移到label
内并使用:focus-within
(注意:目前无法在IE或Edge浏览器中使用)
.test-label {
color: purple;
}
.test-label:focus-within {
color: blue;
}
&#13;
<form>
<label class="test-label">Label
<br />
<input type="text" class="test-box">
</label>
</form>
&#13;
答案 2 :(得分:1)
在
label
之后保持input
并应用General Sibling Selector,并标记position:absolute
以保持label
位置在最前面
.myInput:focus~label {
color: blue !important;
cursor: pointer;
}
.test-label {
color: purple;
position: absolute;
top: 0;
left: 0;
}
.test-box {
position: relative;
}
.myInput:focus~label {
color: blue !important;
cursor: pointer;
}
.myInput:hover {
color: blue !important;
cursor: pointer;
}
<form class="test-box">
<br />
<input type="text" class="myInput">
<label class="test-label">Label</label>
</form>
,这将在所有现代浏览器上运行。希望这会对你有所帮助。
答案 3 :(得分:0)
从“.test-box:focus”中删除额外的选择器。
.test-label{
color: purple;
}
.test-box:focus {
background-color: blue !important;
}
<form>
<label class = "test-label">Label</label>
<br />
<input type = "text" class = "test-box">
</form>
答案 4 :(得分:0)
.test-label{
color: purple;
}
.test-box:hover .test-label{
color: blue !important;
cursor: pointer;
}
&#13;
<form class="test-box">
<label class = "test-label">Label</label>
<br />
<input type = "text">
</form>
&#13;