输入字段样式



我希望当用户专注于输入字段时,输入字段的标签和边框应该是红色的,当用户离开时,输入域的标签和边界都应该变成绿色。此外,当用户聚焦并没有输入任何值时,标签和边框都会再次显示为红色。

.field {
position: relative;
}
.inName {
position: absolute;
outline: none;
z-index: 1;
border: 1px solid silver;
}
.laName {
position: absolute;
top: 7px;
left: 10px;
pointer-events: none;
font-size: 20px;
color: rgb(95, 99, 105);
z-index: 1;
background: #fff;
transition: .3s;
}
.inName:focus+.laName {
top: -12px;
font-size: 15px;
padding: 0 5px;
color: crimson;
}
.inName:not(:placeholder-shown).inName:not(:focus)+.laName {
position: absolute;
top: -12px;
pointer-events: none;
padding: 0 5px;
font-size: 15px;
background-color: #ffffff;
color: crimson;
z-index: 1;
transition: .3s;
}
.inName:focus {
border: 1px solid crimson;
}
<div class="field name">
<input type="text" class="inName" placeholder=" ">
<label for="" class="laName">Name</label>
</div>

在这里,我认为您可以在.inName:not(:placeholder-shown).inName:not(:focus)+.laName类中添加color:green,还可以添加另一个将边界设置为绿色的类.inName:not(:placeholder-shown).inName:not(:focus)。这是您的更改代码(我评论了更改的位置(:

<!DOCTYPE html><html>
<head>
<style>
.field {
position: relative;
}
.inName {
position: absolute;
outline: none;
z-index: 1;
border: 1px solid silver;
}
.laName { 
position: absolute;
top: 7px;
left: 10px;
pointer-events: none;
font-size: 20px;
color: rgb(95, 99, 105);
z-index: 1;
background: #fff;
transition: .3s;
}
.inName:focus+.laName {
top: -12px;
font-size: 15px;
padding: 0 5px;
color: crimson;
}
.inName:not(:placeholder-shown).inName:not(:focus)+.laName {
position: absolute;
top: -12px;
pointer-events: none;
padding: 0 5px;
font-size: 15px;
background-color: #ffffff;
/*CHANGE HERE COLOR TO GREEN*/
color: green;
z-index: 1;
transition: .3s;
}
.inName:focus {
border: 1px solid crimson;
} 
/*ADD THIS*/
.inName:not(:placeholder-shown).inName:not(:focus){
border: 1px solid green;
}

</style>
</head>
<body>
<div class="field name">
<input type="text" class="inName" placeholder=" ">
<label for="" class="laName">Name</label>
</div>

</body>
</html>


这可以使用JS事件侦听器-focuschange来完成

以下是您可以做的快速操作:

document.getElementsByTagName("input")[0].addEventListener("focus", focus);
document.getElementsByTagName("input")[0].addEventListener("change", focus);
function focus() {
var input = document.getElementsByTagName("input")[0];
if (input.value.length === 0) {
input.style.borderColor = "red"; // for input
input.nextElementSibling.style.color = "red"; // for label
} else {
input.style.borderColor = "green"; // for input
input.nextElementSibling.style.color = "green"; // for label
}
}

还将CSS中的输入边框颜色设置为绿色,作为第一次加载的默认颜色。

最新更新