如何创建:标签页标题

学习如何使用 CSS 和 JavaScript 创建标签页标题。

标签页标题

请单击 "city" 按钮,以显示相应的标题:

London

London is the capital city of England.

Paris

Paris is the capital of France.

Tokyo

Tokyo is the capital of Japan.

Oslo

Oslo is the capital of Norway.

亲自试一试

创建可切换的标签页标题

第一步 - 添加 HTML:

<div id="London" class="tabcontent">
  <h1>London</h1>
  <p>London is the capital city of England.</p>
</div>
<div id="Paris" class="tabcontent">
  <h1>Paris</h1>
  <p>Paris is the capital of France.</p>
</div>
<div id="Tokyo" class="tabcontent">
  <h1>Tokyo</h1>
  <p>Tokyo is the capital of Japan.</p>
</div>
<div id="Oslo" class="tabcontent">
  <h1>Oslo</h1>
  <p>Oslo is the capital of 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>
创建按钮以打开特定的标签页内容。所有具有类 "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;}

ບາງການທີ3 - ສະໜອງ 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();

亲自试一试

相关页面

教程:如何创建标签页