<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#div1{width: 250px;
height: 250px;
border: 1px solid black;
padding: 50px;
text-align: center;
margin: 100px auto;
background-color:lightgray}
#div1 input{width: 250px; height: 30px; font-size: 18px; margin-top: 20px}
#div1 span{margin-top: 5px; font-size: 14px; color: gray}
#div1 .testCode{width: 70px; height: 30px; line-height: 30px;
background-color: gray; color: white; float: left;
margin-left: 12px; margin-top: 10px
}
</style>
<script>
window.onload = function(){
var user = document.getElementById("username");
var userspan = document.getElementById("username_span");
var password = document.getElementById("password");
var testCode = document.getElementsByClassName("testCode");
user.onblur = function(){
var value = user.value;
if(value.length<6 || value.length >18){
userspan.innerHTML = '❗️长度应为6~18个字符';
userspan.style.color = 'red';
}
else if(/^\d$/.test(value[0])){ //判断开头是否是英文字母
userspan.innerHTML = '❗️邮件地址必需以英文字母开头';
userspan.style.color = 'red';
}
else if(/\W/.test(value)){
userspan.innerHTML = '❗️邮件地址需由字母、数字或下划线组成 ';
userspan.style.color = 'red';
}
else {
userspan.innerHTML = "✅该用户名可注册";
userspan.style.color = 'green';
}
}
password.onblur = function(){
var value2 = password.value;
//每次开始前都把方块颜色改为灰色
for(var i = 0; i < testCode.length; i++){
testCode[i].style.backgroundColor = 'gray';
}
if(value2.length >= 6 && value2.length<=18){
if(/^\d+$/.test(value2) || /^[a-z]]+$/.test(value2) || /^[A-Z]]+$/.test(value2)){
testCode[0].style.backgroundColor = 'green';
}
//同时拥有数字 小写字母和大写字母
else if(/\d/.test(value2) && /[a-z]/.test(value2) && /[A-Z]/.test(value2)){
testCode[2].style.backgroundColor = 'green';
}
//麻烦的情况写在最后用else
else{
testCode[1].style.backgroundColor = 'green';
}
}else{
password.value = '';
alert('❗️长度应为6~18个字符');
}
}
}
</script>
</head>
<body>
<div id = 'div1'>
<input id = 'username' type="text" placeholder="用户名"/>
<span id = 'username_span'>6~18个字符,可使用字母、数字、下划线,需以字母开头</span>
<input id = 'password' type="text" placeholder="密码"/>
<div class = 'testCode'>弱</div>
<div class = 'testCode'>中</div>
<div class = 'testCode'>强</div>
</div>
</body>
</html>