如何創建:標簽頁標題
學習如何使用 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> Create buttons to open specific tab content. All <div> elements with class="tabcontent" are hidden by default (with CSS & JS). When the user clicks on a button - it will open the tab content that "matches" this button.
第二步 - 添加 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();
相關頁面
教程:如何創建標簽頁