Computer >> Máy Tính >  >> Lập trình >> Javascript

Làm cách nào để tạo menu thả xuống có thể nhấp bằng CSS và JavaScript?


Sau đây là mã để tạo trình đơn thả xuống có thể nhấp bằng CSS và JavaScript -

Ví dụ

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
.menu-btn {
   background-color: #7e32d4;
   color: white;
   padding: 16px;
   font-size: 20px;
   font-weight: bolder;
   font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
   border: none;
}
.dropdown-menu {
   position: relative;
   display: inline-block;
}
.menu-content {
   display: none;
   position: absolute;
   background-color: #017575;
   min-width: 160px;
   z-index: 1;
}
.links {
   color: rgb(255, 255, 255);
   padding: 12px 16px;
   text-decoration: none;
   display: block;
   font-size: 18px;
   font-weight: bold;
   border-bottom: 1px solid black;
}
.links:hover {
   background-color: rgb(8, 107, 46);
}
.dropdown-menu:hover .menu-btn {
   background-color: #3e8e41;
}
</style>
</head>
<body>
<h2>Click on the below dropdown button to open/close dropdown menu</h2>
<div class="dropdown-menu">
<button class="menu-btn">Open <</button>
<div class="menu-content">
<a class="links" href="#">Contact Us</a>
<a class="links" href="#">Visit Us</a>
<a class="links" href="#">About Us</a>
</div>
</div>
<script>
let dropdownBtn = document.querySelector('.menu-btn');
let menuContent = document.querySelector('.menu-content');
dropdownBtn.addEventListener('click',()=>{
   if(menuContent.style.display===""){
      menuContent.style.display="block";
   } else {
      menuContent.style.display="";
   }
})
</script>
</body>
</html>

Đầu ra

Đoạn mã trên sẽ tạo ra kết quả sau -

Làm cách nào để tạo menu thả xuống có thể nhấp bằng CSS và JavaScript?

Khi nhấp vào nút mở -

Làm cách nào để tạo menu thả xuống có thể nhấp bằng CSS và JavaScript?