如何創建:垂直標簽頁

學習如何使用 CSS 和 JavaScript 創建垂直標簽頁菜單。

垂直標簽頁

標簽頁非常適合單頁 Web 應用程序或能夠顯示不同主題的網頁。

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" onclick="openCity(event, 'London')">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="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:

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

* {box-sizing: border-box}
/* Style the tab */
.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;
  transition: 0.3s;
}
/* 更改懸停時按鈕的背景顏色 */
.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;
}

第三步 - 添加 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";
}

親自試一試

相關頁面

教程:如何創建水平標簽頁