JSFiddle - React, Tailwind, and code Playground
by birdie2019
HTML
<div class="container">
<button onclick="loginModal()">點我登入帳號</button>
<hr>
<button onclick="postModal()">點我新增貼文</button>
<div class="modal" id="login-modal">
<div>
<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>
<div>標題:<input type="text"></div>
<div>內文:<br><textarea></textarea></div>
<hr>
<button class="btn-close">關閉</button>
</div>
</div>
</div>
CSS
* {
box-sizing: border-box;
letter-spacing: 1px;
}
.container {
width: 600px;
margin: 10px auto;
}
.container button {
width: 120px;
background-color: #14375e;
border-radius: 20px;
padding: 10px;
border: 0;
letter-spacing: 1px;
color: #fff;
cursor: pointer;
}
.modal {
z-index: 1;
width: 100%;
height: 100vh;
padding: 20px;
background-color: #eee;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: rgba(0, 0, 0, 0.4);
}
.modal > div {
background-color: #fff;
width: 300px;
padding: 30px;
border-radius: 5px;
box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.3);
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.modal > div div {
margin-bottom: 10px;
}
.modal > div button {
width: 50px;
border-radius: 0;
background-color: rgb(0, 127, 119);
}
.modal > div input, .modal > div textarea {
width: 100%;
padding: 5px;
}
JavaScript
var loginMd = document.querySelector('#login-modal');
var postMd = document.querySelector('#post-modal');
var modals = document.querySelectorAll('.modal');
for (var modal of modals) {
modal.style.display = 'none';
var closeBtn = modal.querySelector('.btn-close');
closeBtn.onclick = closeModal;
}
function loginModal() {
loginMd.style.display = 'block';
}
function postModal() {
postMd.style.display = 'block';
}
function closeModal () {
event.target.closest('.modal').style.display = 'none';
}
window.onclick = function() {
console.log(event.target);
if (event.target == loginMd) {
loginMd.style.display = "none";
} else if (event.target == postMd) {
postMd.style.display = "none";
}
}