源码:
<!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>
div{
width: 600px;
margin: 100px auto;
}
.message{
display: inline-block;
font-size: 12px;
color: #999;
background: url(images/mess.png) no-repeat left center;
padding-left: 20px;
}
.wrong{
color: red;
}
.right{
color: aquamarine;
}
</style>
</head>
<body>
<div class="register">
<input type="password" name="" value="" class="ipt">
<p class="message">请输入6-16位密码</p>
</div>
<script>
//1.获取元素
var ipt = document.querySelector('.ipt');
var message = document.querySelector('message');
//2.注册事件,失去焦点事件
ipt.onblur = function(){
//根据表单里面值的长度 ipt.value.length
if(this.value.length < 6 || this.value.length > 16){
//console.log('大于16或小于6')
message.className = 'message wrong';
message.innerHTML = '你输入的为数不对要求6~16位';
}else{
message.className = 'message right';
message.innerHTML = '你输入的格式正确';
}
}
</script>
</body>
</html>
以下两句代码段报错
message.className = 'message wrong';
message.className = 'message right';
经过排查发现是因为获取元素的时候少了一个“.”
var message = document.querySelector('message');
将var message = document.querySelector('message');改成var message = document.querySelector('.message');
错误解决