如果需要,CSS 输入效果不起作用,已删除

rah*_*tel 4 html css

如果输入标签中有需要,标签效果将起作用。但如果我删除所需的属性,效果将不起作用单击查看工作小提琴 是否有任何解决方案。

html

<div class="group ">
<input type="text" required="" class="module-input" />
<label >Name</label>
</div>
Run Code Online (Sandbox Code Playgroud)

片段:

<div class="group ">
<input type="text" required="" class="module-input" />
<label >Name</label>
</div>
Run Code Online (Sandbox Code Playgroud)
.module-input {
  font-size: 14px;
  padding-top: 12px;
  display: block;
  width: 97%;
  border: none;
  border-bottom: 1px solid #94a3a9;
  background-color: transparent;
  color: #5a686d;
  margin-bottom: 2%;
}

input:focus {
  outline: none;
}

.group {
  position: relative;
  margin-bottom: 25px;
}


/* LABEL */

label {
  color: #94a3a9;
  font-size: 14px;
  font-weight: normal;
  position: absolute;
  pointer-events: none;
  left: 0.5%;
  top: 10px;
  transition: 0.2s ease all;
  -moz-transition: 0.2s ease all;
  -webkit-transition: 0.2s ease all;
}


/* active state */

input:focus+label,
input:valid+label {
  top: -8px;
  font-size: 12px;
  color: #94a3a9;
}
Run Code Online (Sandbox Code Playgroud)

LGS*_*Son 6

如果您使用属性选择器更新规则,则无论有或没有属性input[required]:valid ~ label,它都会起作用required

发生的情况是,当某个属性input不具有reqiured被视为有效的属性时,规则会立即生效。

更新

为了能够正确处理这个问题,因为不适:empty用于input元素,我添加了一个小脚本和一个属性选择器,它们在更改时设置,然后 CSS 规则检查它是否为空

window.addEventListener('load', function() {
  var inp = document.querySelectorAll('input');
  for (var i = 0; i < inp.length; i++) {
    inp[i].addEventListener('change', function() {
      this.setAttribute("data-value", this.value);
    })
  }
})
Run Code Online (Sandbox Code Playgroud)
.module-input {
  font-size: 14px;
  padding-top: 12px;
  display: block;
  width: 97%;
  border: none;
  border-bottom: 1px solid #94a3a9;
  background-color: transparent;
  color: #5a686d;
  margin-bottom: 2%;
}

input:focus {
  outline: none;
}

.group {
  position: relative;
  margin-bottom: 25px;
}


/* LABEL */

label {
  color: #94a3a9;
  font-size: 14px;
  font-weight: normal;
  position: absolute;
  pointer-events: none;
  left: 0.5%;
  top: 10px;
  transition: 0.2s ease all;
  -moz-transition: 0.2s ease all;
  -webkit-transition: 0.2s ease all;
}


/* active state */

input[data-value]:not([data-value=""]) ~ label,
input:focus ~ label {
  top: -8px;
  font-size: 12px;
  color: #94a3a9;
}
Run Code Online (Sandbox Code Playgroud)
<div class="group ">
  <input type="text" class="module-input" required="" />
  <label>Name</label>
</div>
<div class="group ">
  <input type="text" class="module-input" />
  <label>Address</label>
</div>
Run Code Online (Sandbox Code Playgroud)