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

Tạo section thu gọn/mở rộng (Collapsible) với CSS và JavaScript

Để tạo một section có thể thu gọn/mở rộng (collapsible) với CSS và JavaScript:

Ví dụ

<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style>    body {       font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;    }    .collapse {       background-color: rgb(83, 186, 255);       color: white;       cursor: pointer;       padding: 18px;       width: 100%;       border: none;       text-align: left;       outline: none;       font-size: 18px;    }    .active, .collapse:hover {       background-color: rgb(34, 85, 160);    }    .content {       padding: 0 18px;       display: none;       overflow: hidden;       background-color: #b6fdff;       font-size: 18px;    } </style> </head> <body> <h1>Ví dụ Collapsible</h1> <h2>Click vào nút dưới để hiển thị nội dung</h2> <button type="button" class="collapse">Mở Collapsible</button> <div class="content"> <h3> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Optio, ducimus! </h3> </div> <script>    var collapse = document.querySelector(".collapse");    collapse.addEventListener("click", function() {       this.classList.toggle("active");       var content = this.nextElementSibling;       if (content.style.display === "block") {          content.style.display = "none";       } else {          content.style.display = "block";       }    }); </script> </body> </html>

Kết quả

Click nút "Mở Collapsible" để hiển thị/ẩn nội dung bên dưới.