了解如何使用 CSS 和 JavaScript 创建选项卡标题。
单击"city" 按钮以显示相应的标题:
伦敦是英格兰的首都。
巴黎是法国的首都。
东京是日本的首都。
奥斯陆是挪威的首都。
<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>
创建按钮以打开特定选项卡内容。所有 <div> 元素class="tabcontent"
默认情况下隐藏(使用 CSS 和 JS)。当用户单击按钮时 - 它将打开"matches"此按钮的选项卡内容。
设置按钮和选项卡内容的样式:
/* Style the tab buttons */
.tablink {
background-color: #555;
color: white;
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
font-size: 17px;
width: 25%;
}
/* Change background color of buttons on hover */
.tablink:hover {
background-color: #777;
}
/* Set default styles for tab content */
.tabcontent {
color: white;
display: none;
padding: 50px;
text-align: center;
}
/* Style each tab content individually */
#London {background-color:red;}
#Paris {background-color:green;}
#Tokyo {background-color:blue;}
#Oslo {background-color:orange;}
function openCity(cityName, elmnt, color) {
// Hide all elements with class="tabcontent" by default */
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Remove the background color of all tablinks/buttons
tablinks = document.getElementsByClassName("tablink");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].style.backgroundColor = "";
}
// Show the specific tab content
document.getElementById(cityName).style.display = "block";
// Add the specific color to the button used to open the tab content
elmnt.style.backgroundColor = color;
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
亲自试一试 »
提示:还请查看操作方法 - 选项卡。
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!