如何通过CSS在聚焦输入框上标记颜色?

时间:2017-10-12 15:54:31

标签: html css

我想在输入焦点上着色标签的效果。就像我对焦输入框一样,标签颜色应该变为蓝色。但这不起作用,我想知道为什么以及如何解决这个问题?



.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;
&#13;
&#13;

5 个答案:

答案 0 :(得分:2)

您可以使用focus-within

Note it has limited support.

import { LoginScreen } from Paths
.test-label {
  color: purple;
}

form:focus-within .test-label {
  color: blue;
}

答案 1 :(得分:2)

input移到label内并使用:focus-within(注意:目前无法在IE或Edge浏览器中使用)

&#13;
&#13;
.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;
&#13;
&#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)

&#13;
&#13;
.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;
&#13;
&#13;