选项卡标题
创建于 2024-12-03 /
26
字体:
[默认]
[大]
[更大]
了解如何使用 CSS 和 JavaScript 创建选项卡标题。
选项卡标题
单击 "city" 按钮以显示相应的标题:
London is the capital city of England.
Paris is the capital of France.
Tokyo is the capital of Japan.
Oslo is the capital of Norway.
创建可切换的选项卡标题
步骤 1) 添加 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>
创建按钮以打开特定的选项卡内容。 默认情况下,所有带有 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;}
Advertisement -->
步骤 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(); 亲自试一试 »
提示: 另请查看 如何 - 选项卡。
0 人点赞过