thực hành - tạo popup form

Trong bài thực hành này, chúng ta sẽ tạo một form popup mở lên bằng HTML, CSS và JavaScript.

Popup form


Xem kết quả

Cách tạo một form bật lên


Bước 1) Thêm HTML:

Ví dụ

<div class="containerx">
    <h1>Đăng nhập</h1>
    <form action="/action_page.php" method="post">
        <div class="input">
            <label for="email">Email</label>
            <input type="text" id="email" placeholder="Email" required="required" />
        </div>
        <div class="input">
            <label for="password">Password</label>
            <input type="password" id="password" placeholder="Password" required="required" />
        </div>
        <div class="button">
            <button type="submit">Đăng nhập</button>
            <button id="btn1" type="button">Close</button>
        </div>
    </form>
</div>
<div class="open">
    <button id="btn2" type="button">Open Form</button>
</div>

Bước 2) Thêm CSS:

Ví dụ

/* Tạo kiểu cho vùng chứa form */
.containerx {
    padding:15px 10px;
    background-color:#ddd;
    border-radius:5px;    
    width:300px;
    position:fixed;
    bottom:20px;
    right:20px;
    overflow:hidden;
}
/* Vùng chứa nút mở form */
.open {
    padding:15px 10px;
    width:300px;
    position:fixed;
    bottom:20px;
    right:20px;    
}
/* Tạo kiểu cho phần tử label */
.input > label {
    display:block;
    margin-bottom:5px;    
}
/* Tạo kiểu cho phần tử input */
.input > input {
    width:100%;
    border:none;
    padding:10px;
    margin-bottom:20px;    
    border-radius:5px;
}
/* Nút mở form bị ẩn theo mặc định */
.open > #btn2 {
    background-color:orange;
    display:none;    
}
/* Tạo kiểu chung cho các nút button */
#btn2, .button > button {
    border:none;
    outline:none;
    padding:10px 15px;
    width:100%;
    cursor:pointer;
    color:white;
    border-radius:5px;
    display:block;
    margin-bottom:10px;
    opacity:0.8;    
}
/* Thêm hiệu ứng khi hover */
#btn2:hover, .button > button:hover {
    opacity:1;    
}
/* Thêm màu nền cho nút button thứ 1 trong form */
.button > button:nth-child(1) {
    background-color:royalblue;    
}
/* Thêm màu nền cho nút button thứ 2 trong form */
.button > button:nth-child(2) {
    background-color:red;    
}
/* Thay đổi cách hiển thị khi màn hình nhỏ hơn 700px */
@media screen and (max-width:700px) {
    .open, containerx {
        width:80%;    
    }
}

Bước 3) Thêm JavaScript:

Ví dụ

<script>
    // Khai báo các biến
    var conx, btn1, btn2;
    conx = document.getElementsByClassName('containerx')[0];
    btn1 = document.getElementById('btn1');
    btn2 = document.getElementById('btn2');
    
    // Gán sự kiện onlick đóng form
    btn1.onclick = function() {
        conx.style.display = "none";
        btn2.style.display = "block";    
    }
    
    // Gán sự kiện onclick mở form
    btn2.onclick = function() {
        conx.style.display = "block";
        this.style.display = "none";    
    }
</script>

Xem kết quả