如何刪除模態
學習如何使用 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>