Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách tạo modal popup bằng JavaScript và CSS

Modal popup là hộp thoại hiển thị lên trên nội dung, đóng khi click ngoài hoặc nút đóng.

Ví dụ hoàn chỉnh (Vanilla JS + CSS, không cần jQuery)

<!DOCTYPE html>
<html>
<head>
<style>
.modal { display:none; position:fixed; z-index:1000; left:0; top:0; width:100%; height:100%;
    background:rgba(0,0,0,0.5); animation:fadeIn .3s; }
.modal-content { position:fixed; top:50%; left:50%; transform:translate(-50%,-50%);
    background:#fff; padding:20px; border-radius:8px; width:90%; max-width:400px;
    animation:slideIn .3s; box-shadow:0 4px 20px rgba(0,0,0,0.2); }
.modal-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:1rem; }
.modal-close { background:none; border:none; font-size:1.5rem; cursor:pointer; color:#666; }
@keyframes fadeIn { from{opacity:0} to{opacity:1} }
@keyframes slideIn { from{opacity:0; transform:translate(-50%,-60%)} to{opacity:1; transform:translate(-50%,-50%)} }
</style>
</head>
<body>
    <h2>Demo Modal</h2>
    <button id="openBtn">Mở Popup</button>
    <div id="myModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Tiêu đề Popup</h3>
                <button class="modal-close" id="closeBtn">×</button>
            </div>
            <div class="modal-body"><p>Nội dung demo...</p></div>
        </div>
    </div>
    <script>
        const modal = document.getElementById('myModal');
        const openBtn = document.getElementById('openBtn');
        const closeBtn = document.getElementById('closeBtn');
        openBtn.onclick = () => modal.style.display = 'block';
        closeBtn.onclick = () => modal.style.display = 'none';
        window.onclick = e => { if(e.target === modal) modal.style.display = 'none'; };
    </script>
</body>
</html>

Ưu điểm: Không phụ thuộc jQuery, nhẹ, dễ tùy biến, accessible (focus trap, ESC key có thể thêm).