Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

CSS와 JavaScript로 모달 박스 만드는 방법 완벽 가이드

CSS와 JavaScript를 활용하면 별도의 라이브러리 없이도 간단하게 모달 박스(팝업 창)를 구현할 수 있습니다. 모달은 사용자의 주의를 환기시키거나 중요한 정보를 표시할 때 널리 사용되는 UI 요소입니다.

아래는 CSS와 JavaScript로 모달 박스를 만드는 전체 코드입니다.

예제

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
    body {
        font-family: Arial, Helvetica, sans-serif;
    }
    .modal {
        text-align: center;
        display: none;
        position: fixed;
        z-index: 1;
        padding-top: 100px;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.4);
    }
    .modalContent {
        font-size: 20px;
        font-weight: bold;
        background-color: #fefefe;
        margin: auto;
        padding: 20px;
        border: 1px solid #888;
        width: 80%;
    }
    .close {
        color: rgb(255, 65, 65);
        float: right;
        font-size: 40px;
        font-weight: bold;
    }
    .close:hover, .close:focus {
        color: #ff1010;
        cursor: pointer;
    }
</style>
</head>
<body>
<h1>Modal Example</h1>
<button class="openModal">Open Modal</button>
<h2>Click on the above button to open modal</h2>
<div class="modal">
<div class="modalContent">
<span class="close">×</span>
<p>Sample text inside modal</p>
</div>
</div>
<script>
    var modal = document.querySelector(".modal");
    var btn = document.querySelector(".openModal");
    var span = document.querySelector(".close");
    btn.addEventListener("click", () => {
        modal.style.display = "block";
    });
    span.addEventListener("click", () => {
        modal.style.display = "none";
    });
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    };
</script>
</body>
</html>

코드 동작 원리

CSS 부분: .modal 클래스는 position: fixed로 화면 전체를 덮는 오버레이 역할을 하며, rgba(0, 0, 0, 0.4) 배경색으로 반투명한 어두운 배경을 형성합니다. z-index: 1을 지정해 다른 콘텐츠보다 위에 표시되고, 기본값은 display: none으로 숨겨진 상태입니다.

JavaScript 부분: 'Open Modal' 버튼을 클릭하면 모달의 display 값이 block으로 변경되어 화면에 나타나고, 닫기(X) 버튼을 클릭하거나 모달 바깥의 어두운 배경 영역을 클릭하면 none으로 설정되어 모달이 사라집니다.

실행 결과

위 코드를 실행하면 다음과 같은 화면이 출력됩니다.

CSS와 JavaScript로 모달 박스 만드는 방법 완벽 가이드

Open Modal 버튼을 클릭하면 아래와 같이 모달 박스가 나타납니다.

CSS와 JavaScript로 모달 박스 만드는 방법 완벽 가이드