模态框
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="modal.css" />
</head>
<body>
<!-- 头部 -->
<header>
<h2 class="title">我的博客</h2>
<button onclick="showModal()">登录</button>
</header>
<!-- 模态框 -->
<div class="modal">
<!-- 1.半透明的遮罩 -->
<div class="modal-zz" onclick="closeModal()"></div>
<!-- 2.弹层表单 -->
<form action="" class="modal-form">
<fieldset style="display: grid; gap: 1em">
<legend>用户登录</legend>
<input type="text" name="username" placeholder="请输入账号" required />
<input type="password" name="password" placeholder="密码不少于6位" required />
<button>登录</button>
</fieldset>
</form>
</div>
<script src="modal.js"></script>
</body>
</html>
css代码
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
/* 头部标题 */
header {
background-color: #666699;
padding: 0.5em 1em;
display: flex;
}
/* logo */
header .title {
font-weight: bold;
font-style: italic;
color: white;
letter-spacing: 10px;
text-shadow: 1px 1px 1px #555;
}
/* 登录按钮 */
header button {
margin-left: auto;
width: 5em;
border: none;
border-radius: 5px;
}
header button:hover {
cursor: pointer;
background-color: blue;
color: #fff;
box-shadow: 0 0 5px #fff;
transition: 0.3s;
}
header button:active {
cursor: pointer;
background-color: red;
color: #fff;
}
/* 模态框 */
.modal .modal-form fieldset {
height: 15.5em;
background-color: lightcyan;
border: none;
padding: 2em 3em;
box-shadow: 0 0 5px #888;
width: 400px;
}
/* 模态框表单标题 */
.modal .modal-form fieldset legend {
padding: 7px 1.5em;
background-color: #009966;
color: white;
border-radius: 5px;
}
.modal .modal-form fieldset input {
height: 3em;
margin: 1px;
padding-left: 1em;
outline: none;
border: 1px solid #ddd;
font-size: 14px;
border-radius: 2px;
}
.modal .modal-form fieldset input:focus {
box-shadow: 1px 1px 5px #888;
border: none;
/* border: 1px solid blue; */
}
.modal .modal-form fieldset button {
background-color: #009966;
color: white;
border: none;
height: 3em;
font-size: 16px;
height: 2.5em;
border-radius: 5px;
}
.modal .modal-form fieldset button:hover {
background-color: coral;
transition: 0.3s;
cursor: pointer;
box-shadow: 0 0 5px #888;
}
/* 定位 */
.modal .modal-form {
position: fixed;
left: calc((100% - 400px) / 2);
top: calc((100% - 15.5em) / 2);
}
/* 遮罩 */
.modal .modal-zz {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.5);
}
.modal {
display: none;
}
js代码
function showModal() {
// 获取模态框元素
const modal = document.querySelector('.modal');
// 显示模态框
modal.style.display = 'block';
// 焦点自动置入第一个输入框email
modal.querySelector('input:first-of-type').focus();
}
function closeModal() {
// 获取模态框元素
const modal = document.querySelector('.modal');
// 关闭模态框
modal.style.display = 'none';
}