首页 > 解决方案 > 为什么 input:invalid 被用作默认而不是主输入样式?

问题描述

我也参考了一些帖子和这个stackoverflow链接:将输入设置为无效但没有多大帮助。

我想要实现的是普通样式输入,当用户关注输入时,我们改变了边框颜色。当我们有一个有效的值时,我们用 input:valid 设置它的样式,否则我们用 input:invalid 设置它的样式。

我几乎已经实现了这一点,但是 input:invalid 样式被用作默认值。我想让边框/背景最初透明。

body {
  height: 100vh;
  display: grid;
  align-items: center;
  margin: 0;
  padding: 0 60px;
}

div {
  display: grid;
  position: relative;
  max-width: 500px;
  margin: 0 auto;
}

input:focus,
input:hover {
  border-bottom-color: dodgerblue;
}

input:invalid {
  border-bottom-color: red;
  background: red;
  color: white;
}

input:valid {
  border-bottom-color: green;
  background: green;
  color: white;
}

input:valid+.icon:after {
  font-family: "Font Awesome 5 Free";
  content: "\f599";
  color: white;
  font-weight: 900;
}

input:invalid+.icon:after {
  font-family: "Font Awesome 5 Free";
  content: "\f119";
  font-weight: 900;
  color: white;
}

.icon {
  position: absolute;
  right: 0;
  height: 35px;
  width: 35px;
  display: grid;
  place-items: center;
}

input {
  border: none;
  outline: none;
  border-bottom: 2px solid black;
  height: 35px;
  padding: 10px;
  padding-right: 35px;
  box-sizing: border-box;
  transition: all 500ms linear;
}
<div>

  <input type="email" pattern="[a-zA-Z0-9.!#$%&amp;’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+" title="enter your email" placeholder="enter your email" required>
  <span class="icon">
        
      </span>
</div>

标签: htmlcssvalidation

解决方案


您可以将:placeholder-shown选择器用于空状态。有元素的:blank选择器input,但目前是实验性的。

body{
  height:100vh;
  display:grid;
  align-items:center;
  margin:0;
  padding:0 60px;
}
div{
  display:grid;
  position:relative;
  max-width:500px;
  margin:0 auto;
}

input:focus,input:hover{
  border-bottom-color:dodgerblue;
}
input:invalid{
  border-bottom-color:red;
  background:red;
  color:white;
}
input:valid{
  border-bottom-color:green;
  background:green;
  color:white;
}
input:valid + .icon:after{
  font-family: "Font Awesome 5 Free";
   content:"\f599";
  color:white;
  font-weight:900;
}
input:invalid + .icon:after{
  font-family: "Font Awesome 5 Free";
  content:"\f119";
  font-weight:900;
  color:white;
}
.icon{
  position:absolute;
  right:0;
  height:35px;
  width:35px;
  display:grid;
  place-items:center;
}
input{
  border:none;
  outline:none;
  border-bottom:2px solid black;
  height:35px; 
  padding:10px;
  padding-right:35px;
  box-sizing:border-box;
  transition:all 500ms linear;
}
input:placeholder-shown {
  border-bottom-color:pink;
  background:pink;
  color:black;
}
<div>

  <input
    type="email" 
    pattern="[a-zA-Z0-9.!#$%&amp;’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+"
    title="enter your email"
    placeholder="enter your email"
    required>
  <span class="icon">

  </span>
</div>


推荐阅读