用js自定義彈窗
代碼如下:
<!DOCTYPE html> <html lang="zh_CN"> <head> <meta charset="UTF-8"> <title>Title</title> <!--定義彈窗的樣式--> <style> .popup { width: 100vw; height: 100vh; background-color: rgba(0, 0, 0, .5); position: fixed; left: 0; top: 0; bottom: 0; right: 0; display: none; justify-content: center; align-items: center; } .popup-content { width: 400px; height: 200px; background-color: #fff; box-sizing: border-box; padding: 10px 30px; color: black; } .top { width: 100%; border-bottom: 1px solid black; } .info { margin-top: 50px; } </style> <script> //給定一個值,使點 確定按鈕 為 true,點其他為 false var isDelete = false; //顯示彈窗函數,設置display為flex function showPopup() { document.getElementById("popup").style.display = "flex"; } //關閉彈窗函數,設置display為none,傳一個參數,把true和false傳進去 function hidePopup(x, e) { //處理冒泡,event 的 cancelable 事件返回一個布爾值 // 確定按鈕有event參數,不會返回undefined(因為取消和其他區域,沒傳值 默認undefined) if (e != undefined) { e.cancelBubble = true; } document.getElementById("popup").style.display = "none"; isDelete = x; console.log(x); } </script> </head> <body> <!--給定一個按鈕來顯示彈窗--> <button type="button" onclick="showPopup()">彈窗</button> <!--給出彈窗的內容--> <!--彈窗點擊除 確定按鈕 以外的 取消和其他區域 時彈窗都會消失且輸出false,點擊 確定按鈕 時為true--> <div class="popup" id="popup" onclick="hidePopup(false)"> <div class="popup-content"> <div class="top"> <p>提示信息</p> </div> <div class="info"> <p>確認關閉?</p> </div> <div class="btn"> <!--因為兩個按鈕在popup這個大框里,點擊確定和取消就會同時點擊父元素,會產生事件冒泡(即點擊確定,會同時出現true和false)--> <button type="button" onclick="hidePopup(true,event)">確定</button> <button type="button" onclick="hidePopup(false)">取消</button> </div> </div> </div> </div> </body> </html>