Cara membuat: Judul tab

Belajar cara membuat judul tab dengan CSS dan JavaScript.

Judul tab

Klik tombol "city" untuk menampilkan judul yang relevan:

London

London adalah ibu kota kota Inggris.

Paris

Paris adalah ibu kota Perancis.

Tokyo

Tokyo adalah ibu kota Jepang.

Oslo

Oslo adalah ibu kota Norwegia.

Coba sendiri

Buat judul tab yang dapat diubah

Langkah pertama - Tambahkan HTML:

<div id="London" class="tabcontent">
  <h1>London</h1>
  <p>London adalah ibu kota Inggris.</p>
</div>
<div id="Paris" class="tabcontent">
  <h1>Paris</h1>
  <p>Paris ialah ibu kota Perancis.</p>
</div>
<div id="Tokyo" class="tabcontent">
  <h1>Tokyo</h1>
  <p>Tokyo ialah ibu kota Jepun.</p>
</div>
<div id="Oslo" class="tabcontent">
  <h1>Oslo</h1>
  <p>Oslo ialah ibu kota Norway.</p>
</div>
<button class="tablink" onclick="openCity('London', this, 'red')" id="defaultOpen">London</button>
<button class="tablink" onclick="openCity('Paris', this, 'green')">Paris</button>
<button class="tablink" onclick="openCity('Tokyo', this, 'blue')">Tokyo</button>
<button class="tablink" onclick="openCity('Oslo', this, 'orange')">Oslo</button>
创建按钮以打开特定的标签页内容。所有具有 class="tabcontent" 的 <div> 元素默认隐藏(使用 CSS & JS)。当用户点击按钮时 - 它将打开与该按钮 "匹配" 的标签页内容。

第二步 - 添加 CSS:

设置按钮和标签页内容的样式:

/* 设置标签页按钮的样式 */
.tablink {
  background-color: #555;
  color: white;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  font-size: 17px;
  width: 25%;
}
/* 更改悬停时按钮的背景颜色 */
.tablink:hover {
  background-color: #777;
}
/* 设置标签页内容的默认样式 */
.tabcontent {
  color: white;
  display: none;
  padding: 50px;
  text-align: center;
}
/* 单独设置每个标签页内容的样式 */
#London {background-color:red;}
#Paris {background-color:green;}
#Tokyo {background-color:blue;}
#Oslo {background-color:orange;}

第三步 - 添加 JavaScript:

function openCity(cityName, elmnt, color) {
  // 默认隐藏所有 class="tabcontent" 的元素 */
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  // 刪除所有標籤頁鏈接/按鈕的背景顏色
  tablinks = document.getElementsByClassName("tablink");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].style.backgroundColor = "";
  }
  // 顯示特定標籤頁內容
  document.getElementById(cityName).style.display = "block";
  // 為用於打開標籤頁內容的按鈕添加特定的顏色
  elmnt.style.backgroundColor = color;
}
// 取得 id="defaultOpen" 的元素並點擊它
document.getElementById("defaultOpen").click();

Coba sendiri

Halaman yang relevan

Tutorial:Bagaimana untuk membuat tab