模态框小实例
<!DOCTYPE html>
<html lang="zh-CN">
<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>
</head>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.notes{
width: 100px;
height: 100px;
background-color: coral;
position: fixed;
top: 200px;
right: 0;
text-align: center;
line-height: 100px;
color: #fff;
}
/* 遮罩层 */
.modal .modal-bg{
position: fixed;
/* 坐标全部清0,请定位到四个顶点 */
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgb(0,0,0,.5);
}
/* 弹出层模态框 */
/* 定位 */
.modal .modal-form {
position: fixed;
top: 10em;
left: 28em;
right: 28em;
}
.modal .modal-form fieldset {
height: 22em;
background-color: lightcyan;
border: none;
padding: 2em 3em;
box-shadow: 0 0 5px #888;
}
.modal .modal-form fieldset legend{
color: #fff;
background-color: coral;
padding: 8px 2em;
}
.modal .modal-form fieldset textarea{
width:45em;
outline: none;
border: 1px solid #ddd;
font-size: 14px;
margin-top: 8px;
}
.modal .modal-form fieldset input{
width:22em;
outline: none;
border: 1px solid #ddd;
font-size: 14px;
margin-top: 8px;
height: 30px;
margin-left: 8px;
}
.modal .modal-form fieldset button{
width: 14em;
margin-left: 10px;
outline: none;
border: 1px solid #ddd;
height: 30px;
background-color: coral;
cursor: pointer;
color: #fff;
}
.modal{
display: none;
}
</style>
<script>
//显示模态框
function showModal(){
//获取模态框元素
const modal = document.querySelector('.modal');
//显示模态框
modal.style.display = 'block';
//焦点自动置入第一个文本域
modal.querySelector('textarea').focus();
}
//关闭模态框
function closeModal(){
//获取模态框元素
const modal = document.querySelector('.modal');
//关闭模态框
modal.style.display = 'none';
}
</script>
<body>
<div class="notes" onclick="showModal()">点我留言</div>
<!-- 模态框 -->
<div class="modal">
<!-- 模态框遮罩层 -->
<div class="modal-bg" onclick="closeModal()"></div>
<!-- 弹出层 -->
<div class="modal-form">
<fieldset>
<legend>市长信箱</legend>
<label for="your-notes">您的留言:</label><textarea name="notes" id="your-notes" cols="30" rows="10" placeholder="请输入您的留言"></textarea>
<label for="your-email">您的邮箱:</label><input type="email" name="email" id="your-email" placeholder="请输入您的邮箱如:123@com">
<button>提 交</button>
</fieldset>
</div>
</div>
</body>
</html>