HTML
<!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>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form action="" method="post" id="login">
<label class="title">用户登录</label>
<label for="email">邮箱:</label>
<input type="email" id="email" name="email" value="" autofocus />
<label for="password">密码:</label>
<input type="password" id="password" name="password" />
<!-- 1. type="button" 来表示这是一个普通按钮,没有提交行为 -->
<button name="submit" onclick="check(this)">登录</button>
</form>
<script>
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>
style.css(表单样式)
body {
background-color: mediumturquoise;
color: #444;
font-weight: lighter;
}
#login {
width: 20em;
border-radius: 0.3em;
box-shadow: 0 0 1em #888;
box-sizing: border-box;
padding: 1em 2em 1em;
margin: 5em auto;
background-color: paleturquoise;
display: grid;
grid-template-columns: 3em 1fr;
gap: 1em 0;
}
#login .title {
grid-area: auto / span 2;
place-self: center;
}
#login input {
border-radius: 0.3em;
border: none;
padding-left: 0.3em;
}
#login input:focus {
outline: none;
box-shadow: 0 0 5px seagreen;
background-color: hsl(283, 100%, 95%);
border-radius: 0.2em;
transition: 0.5s;
}
#login button {
grid-area: auto / 2 / auto;
outline: none;
background-color: lightseagreen;
border: none;
height: 2em;
color: #fff;
}
#login button:hover {
cursor: pointer;
background-color: seagreen;
transition: 0.5s;
}