如何删除模态
学习如何使用 CSS 创建删除确认模态框。
点击按钮打开模态框:
×
如何创建删除模态框
第一步 - 添加 HTML:
<button onclick="document.getElementById('id01').style.display='block'">Open Modal</button>
<div id="id01" class="modal">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<form class="modal-content" action="/action_page.php">
<div class="container">
<h1>Delete Account</h1>
<p>Are you sure you want to delete your account?</p>
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="button" class="deletebtn">Delete</button>
</div>
</div>
</form>
</div>
第二步 - 添加 CSS:
* {box-sizing: border-box}
/* 为所有按钮设置样式 */
button {
background-color: #04AA6D;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
}
button:hover {
opacity:1;
}
/* 使取消和删除按钮浮动,并添加相等的宽度 */
.cancelbtn, .deletebtn {
float: left;
width: 50%;
}
/* 为取消按钮添加颜色 */
.cancelbtn {
background-color: #ccc;
color: black;
}
/* 为删除按钮添加颜色 */
.deletebtn {
background-color: #f44336;
}
/* 为容器添加内边距并居中文本 */
.container {
padding: 16px;
text-align: center;
}
/* 模态(背景) */
.modal {
display: none; /* 默认隐藏 */
position: fixed; /* 固定在原地 */
z-index: 1; /* 置于顶层 */
left: 0;
top: 0;
width: 100%; /* 全宽 */
height: 100%; /* 全高 */
overflow: auto; /* 启用滚动(如果需要) */
background-color: #474e5d;
padding-top: 50px;
}
/* 模态内容/框 */
.modal-content {
background-color: #fefefe;
margin: 5% auto 15% auto; /* 距顶部 5%,距底部 15%,且居中 5% */
border: 1px solid #888;
width: 80%; /* 宽度可以是更多或更少,取决于屏幕大小 */
}
/* 设置水平线的样式 */
hr {
border: 1px solid #f1f1f1;
margin-bottom: 25px;
}
/* 模态框关闭按钮(x) */
.close {
position: absolute;
right: 35px;
top: 15px;
font-size: 40px;
font-weight: bold;
color: #f1f1f1;
}
.close:hover,
.close:focus {
color: #f44336;
cursor: pointer;
}
/* Clear floats */
.clearfix::after {
content: "";
clear: both;
display: table;
}
/* 更改超小屏幕上取消按钮和删除按钮的样式 */
@media screen and (max-width: 300px) {
.cancelbtn, .deletebtn {
width: 100%;
}
}
提示:你还可以使用以下 JavaScript 代码,通过点击模态框内容之外的区域来关闭模态框(而不仅仅是通过点击“x”或“取消”按钮来关闭它):
实例
<script>
// 获取模态框
var modal = document.getElementById('id01');
// 当用户点击模态框之外的任何位置时,将其关闭
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>