<!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>表单验证</title>
<style>
body {
background-color: mediumturquoise;
color: #444;
font-weight: lighter;
}
#login {
background-color: azure;
width: 20em;
border-radius: 0.3em;
box-shadow: 0 0 1em #888;
box-sizing: border-box;
padding: 1em 2em 1em;
margin: 5em auto;
display: grid;
grid-template-columns: 3em 1fr;
gap: 1em 0;
}
.btn1 {
color: red;
}
.btn2 {
background-color:lightgreen;
}
.btn3 {
background-color: blue;
}
</style>
</head>
<body>
<form action="" method="post" id="login" >
<label for="email">邮箱:</label>
<input type="email" id="email" name="email" value="" autofocus>
<label for="password">密码:</label>
<input type="password" name="password" id="password">
<button name="submit" class="btn">登录</button>
</form>
<script>
// 1. 实例演示classList对象
let btn = document.querySelector('.btn');
btn.classList.add('btn1'); // 剩下:btn btn1
console.log(btn.classList.contains('btn'));
btn.classList.add('btn2'); // 剩下:btn btn1 btn2
btn.classList.remove('btn'); // 剩下:btn1 btn2
btn.classList.replace('btn2', 'btn3'); // 剩下:btn1 btn3
btn.classList.toggle('btn3'); // 剩下:btn1
// 2. 使用blur事件进行表单非空验证
document.forms.login.email.onblur = function() {
if (this.value.length === 0){
alert("邮箱不能为空");
return false;
}
};
document.forms.login.password.onblur = function(){
if(this.value.length === 0){
alert("密码不能为空");
return false;
}
};
</script>
</body>
</html>