JavaScript 系列三:練習3 ── modal 互動視窗元件

by max002215

HTML

<button onclick="loginModal()">點我登入帳號</button>
<hr>
<button onclick="postModal()">點我新增貼文</button>

<div class="modal" id="login-modal">
<div class="modal-content">
  <div>帳號:<input type="text"></div>
  <div>密碼:<input type="password"></div>
  <hr>
  <button class="btn-close">關閉</button>
  </div>
</div>
<div class="modal" id="post-modal">
<div class="modal-content">
  <div>標題:<input type="text"></div>
  <div>內文:<textarea></textarea></div>
  <hr>
  <button class="btn-close">關閉</button>
  </div>
</div>

CSS

*{
 box-sizing:border-box;
}
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  padding-top: 100px; /* Location of the box */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0, 0, 0); /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4); /* Black w/ opacity */
}
.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
    
}

JavaScript

let login_modal = document.querySelector('#login-modal');
let post_modal = document.querySelector('#post-modal');
let btn_close = document.querySelectorAll('.btn-close')


function loginModal(){
login_modal.style.display='block';
}
function postModal(){
post_modal.style.display='block'
}
//按鈕關閉的函數
function removeModal() {
  event.target.closest('.modal').style.display='none';
}
for (let btncloses of btn_close) {
  btncloses.onclick = removeModal;
}