如何 TO - 標籤頁標題
學習如何使用 CSS 和 JavaScript 建立標籤頁標題。
標籤頁標題
點選“城市”按鈕即可顯示相應的標題
London
倫敦是英格蘭的首都。
巴黎
巴黎是法國的首都。
東京
東京是日本的首都。
奧斯陸
奧斯陸是挪威的首都。
建立可切換的標籤頁標題
步驟 1) 新增 HTML
示例
<div id="London" class="tabcontent">
<h1>London</h1>
<p>倫敦是英格蘭的首都。</p>
</div>
<div id="Paris" class="tabcontent">
<h1>Paris</h1>
<p>巴黎是法國的首都。</p>
</div>
<div id="Tokyo" class="tabcontent">
<h1>Tokyo</h1>
<p>東京是日本的首都。</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>
建立按鈕以開啟特定的標籤內容。所有具有 class="tabcontent"
的 <div> 元素預設都隱藏(透過 CSS & JS)。當用戶點選一個按鈕時 - 它將開啟與該按鈕“匹配”的標籤內容。
步驟 2) 新增 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/按鈕的背景顏色
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();
自己動手試一試 »
提示:同時檢視 如何 - 標籤頁。