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="zuoye.css" />
</head>
<body>
<header>
<h1 class="title">新手1314的博客</h1>
<button onclick="show()">登录</button>
</header>
<div class="show">
<div class="show-ad" onclick="close()"></div>
<form action="" class="show-form">
<fieldset style="display: grid; gap: 1em">
<legend>用户登录</legend>
<input type="text" name="user" placeholder="请输入用户名" />
<input type="password" name="password" placeholder="请输入密码" />
<button>登录</button>
</fieldset>
</form>
</div>
<script src="zuoye.js"></script>
</body>
</html>
css样式:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
header {
background-color: aqua;
padding: 0.5em 1em;
display: flex;
}
header .title {
color: #fff;
font-weight: lighter;
letter-spacing: 3px;
text-shadow: 1px 1px 1px #000;
}
header button {
margin-left: auto;
border: none;
border-radius: 0.5em;
width: 60px;
}
header button:hover {
cursor: pointer;
background-color: black;
color: beige;
transform: 0.5s;
box-shadow: 0 0 5px #fff;
}
.show .show-form fieldset {
background-color: blanchedalmond;
border: 0;
height: 16em;
padding: 2em 3em;
box-sizing: 0 0 5px #000;
}
.show .show-form fieldset legend {
background-color: violet;
color: #000;
padding: 7px 1.5em;
}
.show .show-form fieldset input {
font-size: 14px;
padding-left: 1em;
outline: none;
border: 2px solid #fff;
height: 3em;
}
.show .show-form fieldset input:focus {
border: 0;
box-shadow: 0 0 8px #888;
}
.show .show-form fieldset button {
background-color: aqua;
color: #000;
border: 0;
font-size: 16px;
height: 2.5em;
}
.show .show-form fieldset button:hover {
cursor: pointer;
background-color: aquamarine;
}
.show .show-form {
position: fixed;
left: 50em;
right: 50em;
top: 10em;
}
.show .show-ad {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgb(0, 0, 0, 0.8);
}
.show {
display: none;
}
js代码:
function show() {
// 获取模态框元素
const show = document.querySelector(".show");
// 显示模态框
show.style.display = "block";
// 焦点自动置入第一个输入框email
show.querySelector("input:first-of-type").focus();
}
function close() {
// 获取模态框元素
const show = document.querySelector(".show");
// 关闭模态框
show.style.display = "none";
}
实现: