How to create: Hoverable tabs

Learn how to use CSS and JavaScript to switch tabs on hover.

Hover tab

Please hover over the menu button to display the tab content:

London

London is the capital city of England.

Paris

Paris is the capital of France.

Tokyo

Tokyo là thủ đô của Nhật Bản.

Thử ngay

Tạo thẻ cuộn dọc có thể trượt

Bước 1 - Thêm HTML:

<div class="tab">
  <button class="tablinks" onmouseover="openCity(event, 'London')">London</button>
  <button class="tablinks" onmouseover="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onmouseover="openCity(event, 'Tokyo')">Tokyo</button>
</div>
<div id="London" class="tabcontent">
  <h3>London</h3>
  <p>London là thủ đô của Anh.</p>
</div>
<div id="Paris" class="tabcontent">
  <h3>Paris</h3>
  <p>Paris là thủ đô của Pháp.</p>
</div>
<div id="Tokyo" class="tabcontent">
  <h3>Tokyo</h3>
  <p>Tokyo là thủ đô của Nhật Bản.</p>
</div>

Tạo nút để mở nội dung thẻ cụ thể. Tất cả các nút có class="tabcontent" của <div> Các yếu tố mặc định đều ẩn (qua CSS và JS). Khi người dùng đặt con trỏ chuột trên nút, nó sẽ mở nội dung thẻ trùng khớp với nút đó.

Bước 2 - Thêm CSS:

Thiết lập樣式 cho nút và nội dung thẻ:

/* Thiết lập樣式 cho thẻ */
.tab {
  float: left;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
  width: 30%;
  height: 300px;
}
/* Thiết lập樣式 cho nút mở nội dung thẻ */
.tab button {
  display: block;
  background-color: inherit;
  color: black;
  padding: 22px 16px;
  width: 100%;
  border: none;
  outline: none;
  text-align: left;
  cursor: pointer;
}
/* Thay đổi màu nền của nút khi chuột trỏ vào */
.tab button:hover {
  background-color: #ddd;
}
/* Tạo lớp "thẻ tab" hoạt động/hiện tại */
.tab button.active {
  background-color: #ccc;
}
/* Đặt样式 cho nội dung tab */
.tabcontent {
  float: left;
  padding: 0px 12px;
  border: 1px solid #ccc;
  width: 70%;
  border-left: none;
  height: 300px;
  display: none;
}

Bước 3 - Thêm JavaScript:

function openCity(evt, cityName) {
  // Định nghĩa tất cả các biến
  var i, tabcontent, tablinks;
  // Lấy tất cả các phần tử có class="tabcontent" và ẩn chúng
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  // Lấy tất cả các phần tử có class="tablinks" và xóa lớp "active"
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  // Hiển thị tab hiện tại và thêm lớp "active" vào liên kết mở tab đó
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

Thử ngay

Trang liên quan

Giáo trình:Cách tạo tab