본문 바로가기
홈 · 카테고리 없음

[javascript/es6] 딤처리 레이어 팝업 예제

by 도라에몽 2021. 8. 6.

자바스크립트 최신문법 딤처리 팝업(모달) 예제

자바스크립트 딤처리 팝업 예제

1. HTML

<button class="modal-btn" href="#modla1">1번 팝업</button>
<div id="modla1" class="modal">
    <div class="modal-content">
        <button class="close">&times;</button>
        <p>1번 팝업.</p>
    </div>
</div>

<button class="modal-btn" href="#modla2">2번 팝업</button>
<div id="modla2" class="modal">
    <div class="modal-content">
        <button class="close">&times;</button>
        <p>2번 팝업.</p>
    </div>
</div>

<button class="modal-btn" href="#modla3">3번 팝업</button>
<div id="modla3" class="modal">
    <div class="modal-content">
        <button class="close">&times;</button>
        <p>3번 팝업.</p>
    </div>
</div>

2. CSS

.modal {
    display: none;
    position: fixed;
    z-index: 1;
    padding-top: 100px;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: #000;
    background-color: rgba(0, 0, 0, .4)
}

.modal-content {
    position: relative;
    background-color: #fefefe;
    margin: auto;
    padding: 0;
    border: 1px solid #888;
    width: 80%;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, .2), 0 6px 20px 0 rgba(0, 0, 0, .19);
    -webkit-animation-name: animatetop;
    -webkit-animation-duration: .4s;
    animation-name: animatetop;
    animation-duration: .4s
}

/* Animation */
@-webkit-keyframes animatetop {
    from {
        top: -300px;
        opacity: 0
    }

    to {
        top: 0;
        opacity: 1
    }
}

@keyframes animatetop {
    from {
        top: -300px;
        opacity: 0
    }

    to {
        top: 0;
        opacity: 1
    }
}

3. Javascript

let modals = document.getElementsByClassName('modal');
let modalBtns = document.getElementsByClassName('modal-btn');
let closeBtns = document.getElementsByClassName('close');

for (let modalBtn of modalBtns) {
    modalBtn.onclick = function(event) {
        document.querySelector(event.target.getAttribute('href')).style.display = 'block';
    }
}

for (let closeBtn of closeBtns) {
    closeBtn.onclick = function(event) {
        event.target.parentNode.parentNode.style.display = 'none';
    }
}

window.onclick = function(event) {
    if (event.target.classList.contains('modal')) {
        for (let modal of modals) {
            if (typeof modal.style !== 'undefined') {
                modal.style.display = 'none';
            }
        }
    }
}

window.onkeydown = function(event) {
    if (event.key == 'Escape') {
        for (let modal of modals) {
            modal.style.display = 'none';
        }
    }
}

딤처리 레이어 팝업 여러개

 

참고:

stackoverflow

댓글