标签颜色不变[重复]

我认为我的代码是正确的,但是当焦点输入时标签颜色不会改变。请让我知道为什么。

https://jsfiddle.net/wvs34qhu/

body {
  font-family: sans-serif;
}
.field {
  position: relative;
  max-width: 250px;
}
label {
  box-sizing: border-box;
  display: block;
  font-size: .8125em;
  padding: .75em 12px;
  pointer-events: none;
  position: absolute;
  text-overflow: ellipsis;
  top: 0;
  text-align: left;

  user-select: none;
  white-space: nowrap;
  width: 100%;
  z-index: 1;
}
input {
  background-color: #f5f5f5;
  border:0;
  border-bottom:2px solid grey;
  font-size: 1.3125em;
  outline:0;
  padding-top:24px;
  padding-left:12px;
  padding-bottom:2px;
  width: 100%;
  
}

input:focus + label{
  color:red;
}

input:focus {
   border-bottom:2px solid red;
}
<div class="field">
  <label for="input-name">Email address</label>
  <input id="input-name" type="name" />
</div>

提前致谢!

评论
  • 本明远
    本明远 回复

    当前不起作用的原因与CSS选择器有关:

    input:focus + label
    

    This explicitly states that in the HTML, the label is directly after the input (which it is not).

    为了使其正常工作,您已经完全确定了标签的位置,可以在HTML中进行切换:

    <div class="field">
      <input id="input-name" type="name" />
      <label for="input-name">Email address</label>
    </div>
    

    选择器现在将按预期工作。请参见以下代码段:

    body {
      font-family: sans-serif;
    }
    .field {
      position: relative;
      max-width: 250px;
    }
    label {
      box-sizing: border-box;
      display: block;
      font-size: .8125em;
      padding: .75em 12px;
      pointer-events: none;
      position: absolute;
      text-overflow: ellipsis;
      top: 0;
      text-align: left;
    
      user-select: none;
      white-space: nowrap;
      width: 100%;
      z-index: 1;
    }
    input {
      background-color: #f5f5f5;
      border:0;
      border-bottom:2px solid grey;
      font-size: 1.3125em;
      outline:0;
      padding-top:24px;
      padding-left:12px;
      padding-bottom:2px;
      width: 100%;
      
    }
    
    input:focus + label{
      color:red;
    }
    
    input:focus {
       border-bottom:2px solid red;
    }
    <div class="field">
      <input id="input-name" type="name" />
      <label for="input-name">Email address</label>
    </div>