html
<!DOCTYPE html>
<html>
<head>
<title>JavaScript表单失去焦点、验证</title>
<link rel="stylesheet" href="css/index.css" />
</head>
<body>
<div id="page">
<h2>欢迎登录</h2>
<form method="post" action="">
<label for="username">用户名: </label>
<input type="text" id="username" /><div id="feedback"></div>
<label for="password">密 码: </label>
<input type="password" id="password" /><div></div>
<input type="submit" value="提交" />
</form>
</div>
<script src="js/index.js"></script>
</body>
</html>
css:
body{
background-color: rgb(0, 0, 0);
position: relative;
}
#page{
background-color: rgb(119, 116, 116);
width: 400px;
height: 400px;
margin: 0 auto 0 auto;
padding: 20px 20px;
}
h2{
margin: 0 auto;
text-align: center;
font-size: 25px;
color: rgb(13, 13, 14);
padding-top:20px;
}
form{
font-size: 24px;
margin: 0 auto;
padding-top: 40px;
}
label{
display: block;
color: aliceblue;
font-size: 20px;
padding-top: 20px;
}
input[type='text'], input[type='password'], textarea {
background-color: rgb(133, 127, 120);
width: 96%;
padding: 4px 6px;
border: 1px solid rgb(92, 90, 90);
border-radius: 20px;
}
input[type='text']:focus, input[type='password']:focus, textarea:focus{
border: 1px solid #fff;
background-color: #fff;
outline: none;
}
input[type='submit']{
color: #fff;
background-color: rgb(235, 171, 171);
width: 50px;
height: 40px;
margin-top: 20px;
float:right;
border-radius: 20px;
cursor: pointer;
}
input[type='submit']:focus{
background-color: rgb(230, 85, 85);
}
#feedback{
font-size: 15px;
padding: 10px 10px;
color: red;
}
JS
//用户名提醒
function checkUsername() {
var username = el.value;
if (username.length < 5) {
elMsg.className = 'warning';
elMsg.textContent = '用户名不够长';
} else {
elMsg.textContent = '';
}
}
function tipUsername() {
elMsg.className = 'tip';
elMsg.innerHTML = '用户名至少5位数';
}
var el = document.getElementById('username');
var elMsg = document.getElementById('feedback');
el.addEventListener('focus', tipUsername, false);
el.addEventListener('blur', checkUsername, false);