onblur 失去光标
onfocus 获得光标
input.value.length 表单里值的长度
this指向的是当前函数的调用者input 如果要改变的不是input 则不能使用this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.msg {
display: inline-block;
color: green;
background: url(../img/right.png) no-repeat left center;
background-size: 20px;
padding-left: 30px;
}
img {
width: 20px;
}
.wrong {
background: url(../img/wrong.png) no-repeat left center;
color: red;
}
.right {
color: green;
}
</style>
</head>
<body>
<input type="text" class="ipt" />
<p class="msg">请输入6-16位密码</p>
<script>
var ipt = document.querySelector('.ipt');
var msg = document.querySelector('.msg');
//失去焦点
ipt.onblur = function() {
if (this.value.length < 6 || this.value.length > 16) {
//在保留原本msg的样式上 增添wrong样式
msg.className = 'msg wrong'
msg.innerHTML = '错误,请输入6-16位';
} else {
msg.className = 'msg right'
msg.innerHTML = '输入正确';
}
}
</script>
</body>
</html>