JavaScript操作表单属性②
- 检查用户输入,高亮显示
要求:用户名不超过10个字符,不低于5个字符
css部分
<style>
input {
height: 40px;
width: 300px;
padding-left: 5px;
border-radius: 5px;
outline: none;
border: 1px solid #eee;
}
label {
position: absolute;
top: 20px;
left: 68px;
color: #ccc;
cursor: text;
}
p {
margin-left: 47px;
font: 14px/30px "microsoft yahei";
color: #F00;
display: none;
}
.wrong {
outline: none;
border: 1px solid #F00;
}
.right {
outline: none;
border: 1px solid #0F0;
}
</style>
body部分
账号:<label for = "inp">请输入用户名:</label><input type="text" id="inp" value="">
<p>提示:用户名的长度需在5-12之间</p>
<script>
var inp = document.getElementsByTagName("input")[0];
var lab = document.getElementsByTagName("label")[0];
var p = document.getElementsByTagName("p")[0];
inp.focus();
inp.oninput = function (){
lab.style.display = "none";
if(inp.value.length <5 || inp.value.length>12){
inp.className = "wrong";
p.style.display = "block";
}
if(inp.value.length>=5&&inp.value.length<=12){
inp.className = "right";
p.style.display = "none";
}
}
inp.onblur = function(){
if(inp.value == ""){
lab.style.display = "block";
inp.className = "";
p.style.display = "none";
}
}
</script>
效果如下图