用javascript写一个tab切换
时间: 2023-05-17 11:07:51 浏览: 140
可以使用以下代码实现tab切换:
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>Some text here...</p>
</div>
<div id="tab2" class="tabcontent">
<h3>Tab 2 Content</h3>
<p>Some text here...</p>
</div>
<div id="tab3" class="tabcontent">
<h3>Tab 3 Content</h3>
<p>Some text here...</p>
</div>
```
CSS:
```
.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 {
display: none;
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";
}
```
在HTML中定义tab按钮和内容,CSS用于样式设置,JavaScript用于实现tab切换功能。在JavaScript中,openTab函数用于切换tab,通过获取tab内容和按钮的类名,来实现显示和隐藏tab内容以及按钮样式的变化。
阅读全文