ja选项卡切换
时间: 2023-07-18 08:04:58 浏览: 41
你可以通过以下步骤来实现JS选项卡切换:
1. 在HTML中创建选项卡标签和对应的内容标签,使用CSS将内容标签隐藏起来。
```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 for Tab 1</p>
</div>
<div id="tab2" class="tabcontent">
<h3>Tab 2 Content</h3>
<p>This is the content for Tab 2</p>
</div>
<div id="tab3" class="tabcontent">
<h3>Tab 3 Content</h3>
<p>This is the content for Tab 3</p>
</div>
```
2. 使用JavaScript编写函数来切换选项卡。该函数将被添加到选项卡按钮的onclick事件中。
```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";
}
```
3. 使用CSS样式来设置选项卡按钮和内容标签的样式。
```css
/* Style the tab */
.tab {
overflow: hidden;
border: 1px solid #ccc;
background-color: #f1f1f1;
}
/* Style the buttons inside the tab */
.tab button {
background-color: inherit;
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: 0.3s;
font-size: 17px;
}
/* Change background color of buttons on hover */
.tab button:hover {
background-color: #ddd;
}
/* Create an active/current tablink class */
.tab button.active {
background-color: #ccc;
}
/* Style the tab content */
.tabcontent {
display: none;
padding: 6px 12px;
border: 1px solid #ccc;
border-top: none;
}
```
4. 最后,在页面加载时默认显示第一个选项卡。
```javascript
document.getElementById("defaultOpen").click();
```
这样就可以实现一个简单的选项卡切换。