html - 为什么 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.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+" title="enter your email" placeholder="enter your email" required>
<span class="icon">
</span>
</div>
解决方案
您可以将: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.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+"
title="enter your email"
placeholder="enter your email"
required>
<span class="icon">
</span>
</div>
推荐阅读
- json - Swift 4 - 无法使用“(可编码)”类型的参数列表调用“编码”
- python - PYSPARK:CX_ORACLE.InterfaceError:不是查询
- python - SimpleITK not working with any data type, be it 3D or 2D
- mysql - 基于通配符替换字符串的 SQL 查询
- r - R比较来自一个数据帧的值与来自另一个数据帧的值
- apache - 使用flume在两个单独的表中写入hive仓库目录中的数据
- javascript - 动态改变 SVG 光标
- swift - 为什么我的操场在 NSRange() 上崩溃
- r - Sum of the multiplication of all columns of one matrix (n-by-m) with another matrix (n-by-n)
- cryptography - 泰雷兹 PayShield HSM 密钥管理