如何創建:可懸停標簽頁

學習如何使用 CSS 和 JavaScript 在鼠標懸停時切換標簽頁。

懸停標簽頁

請將鼠標懸停在菜單按鈕上,以顯示標簽頁內容:

London

London is the capital city of England.

Paris

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.

親自試一試

創建可懸停的垂直標簽頁

第一步 - 添加 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 is the capital city of England.</p>
</div>
<div id="Paris" class="tabcontent">
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div>
<div id="Tokyo" class="tabcontent">
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

創建按鈕以打開特定的標簽頁內容。所有帶有 class="tabcontent"<div> 元素默認都是隱藏的(通過 CSS 和 JS)。當用戶將鼠標懸停在按鈕上時,它將打開與該按鈕“匹配”的標簽頁內容。

第二步 - 添加 CSS:

設置按鈕和標簽頁內容的樣式:

/* 設置標簽頁的樣式 */
.tab {
  float: left;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
  width: 30%;
  height: 300px;
}
/* 設置用于打開標簽頁內容的按鈕的樣式 */
.tab button {
  display: block;
  background-color: inherit;
  color: black;
  padding: 22px 16px;
  width: 100%;
  border: none;
  outline: none;
  text-align: left;
  cursor: pointer;
}
/* 更改按鈕在鼠標懸停時的背景顏色 */
.tab button:hover {
  background-color: #ddd;
}
/* 創建一個活動/當前的“標簽頁按鈕”類 */
.tab button.active {
  background-color: #ccc;
}
/* 設置標簽頁內容的樣式 */
.tabcontent {
  float: left;
  padding: 0px 12px;
  border: 1px solid #ccc;
  width: 70%;
  border-left: none;
  height: 300px;
  display: none;
}

第三步 - 添加 JavaScript:

function openCity(evt, cityName) {
  // 聲明所有變量
  var i, tabcontent, tablinks;
  // 獲取所有帶有 class="tabcontent" 的元素并隱藏它們
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  // 獲取所有帶有 class="tablinks" 的元素并刪除類 "active"
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  // 顯示當前標簽頁,并將 "active" 類添加到打開該標簽頁的鏈接
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

親自試一試

相關頁面

教程:如何創建標簽頁