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>
출력
위의 코드는 다음과 같은 출력을 생성합니다 -
모달 열기를 클릭하면 버튼 -