html tab 选项卡切换代码,JS实现简单tab选项卡切换
时间: 2023-09-29 21:03:17 浏览: 121
HTML代码:
```
<div class="tab">
<button class="tablinks" onclick="openTab(event, 'tab1')">Tab 1</button>
<button class="tablinks" onclick="openTab(event, 'tab2')">Tab 2</button>
<button class="tablinks" onclick="openTab(event, 'tab3')">Tab 3</button>
</div>
<div id="tab1" class="tabcontent">
<h3>Tab 1 Content</h3>
<p>This is the content of Tab 1.</p>
</div>
<div id="tab2" class="tabcontent">
<h3>Tab 2 Content</h3>
<p>This is the content of Tab 2.</p>
</div>
<div id="tab3" class="tabcontent">
<h3>Tab 3 Content</h3>
<p>This is the content of Tab 3.</p>
</div>
```
CSS代码:
```
/* 隐藏所有选项卡内容 */
.tabcontent {
display: none;
}
/* 样式化选项卡按钮 */
.tab {
overflow: hidden;
border: 1px solid #ccc;
background-color: #f1f1f1;
}
.tab button {
background-color: inherit;
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: 0.3s;
}
.tab button:hover {
background-color: #ddd;
}
.tab button.active {
background-color: #ccc;
}
/* 样式化选项卡内容 */
.tabcontent {
padding: 6px 12px;
border: 1px solid #ccc;
border-top: none;
}
```
JavaScript代码:
```
function openTab(evt, tabName) {
// 隐藏所有选项卡内容
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// 取消所有选项卡按钮的激活状态
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
// 显示当前选项卡内容并激活按钮
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
```
以上代码实现了一个简单的选项卡切换效果。点击每个按钮时,会显示对应的选项卡内容,并且激活该按钮。
阅读全文