點選按鈕彈出模態框實現
阿新 • • 發佈:2019-01-07
點選按鈕彈出模態框的實現:
html:
js:<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>模態框</title> <link rel="stylesheet" type="text/css" href="modalBox.css"> </head> <body> <!-- 觸發按鈕 --> <button id="triggerBtn">模態框</button> <!-- 模態框 --> <div id="myModal" class="modal"> <div class="modal-content"> <div class="modal-header"> <h2>頭部</h2> <span id="closeBtn" class="close">×</span> </div> <div class="modal-body"> <p>這是一個模態框!</p> <p>喜歡就點個贊吧!</p> </div> <div class="modal-footer"> <h3>尾部</h3> </div> </div> </div> <script type="text/javascript" src="modalBox.js"></script> </body> </html>
css:(function() { /*建立模態框物件*/ var modalBox = {}; /*獲取模態框*/ modalBox.modal = document.getElementById("myModal"); /*獲得trigger按鈕*/ modalBox.triggerBtn = document.getElementById("triggerBtn"); /*獲得關閉按鈕*/ modalBox.closeBtn = document.getElementById("closeBtn"); /*模態框顯示*/ modalBox.show = function() { console.log(this.modal); this.modal.style.display = "block"; } /*模態框關閉*/ modalBox.close = function() { this.modal.style.display = "none"; } /*當用戶點選模態框內容之外的區域,模態框也會關閉*/ modalBox.outsideClick = function() { var modal = this.modal; window.onclick = function(event) { if(event.target == modal) { modal.style.display = "none"; } } } /*模態框初始化*/ modalBox.init = function() { var that = this; this.triggerBtn.onclick = function() { that.show(); } this.closeBtn.onclick = function() { that.close(); } this.outsideClick(); } modalBox.init(); })();
/*模態框*/ .modal { display: none; /* 預設隱藏 */ position: fixed; /* 根據瀏覽器定位 */ z-index: 1; /* 放在頂部 */ left: 0; top: 0; width: 100%; /* 全寬 */ height: 100%; /* 全高 */ overflow: auto; /* 允許滾動 */ background-color: rgba(0,0,0,0.4); /* 背景色 */ } /*模態框內容*/ .modal-content { display: flex; /*採用flexbox佈局*/ flex-direction: column; /*垂直排列*/ position: relative; background-color: #fefefe; margin: 15% auto; /*距頂部15% 水平居中*/ padding: 20px; border: 1px solid #888; width: 80%; animation: topDown 0.4s; /*自定義動畫,從模態框內容上到下出現*/ } @keyframes topDown { from {top: -300px; opacity: 0} to {top: 0; opacity: 1} } /*模態框頭部*/ .modal-header { display: flex; /*採用flexbox佈局*/ flex-direction: row; /*水平佈局*/ align-items: center; /*內容垂直居中*/ justify-content: space-between; } /*關閉X 樣式*/ .close { color: #aaa; float: right; font-size: 28px; font-weight: bold; } .close:hover { color: black; text-decoration: none; cursor: pointer; }