使用 js 做出 tab 切换的效果
时间: 2023-10-10 18:11:44 浏览: 38
好的,以下是使用 JavaScript 实现 tab 切换的示例代码:
HTML 代码:
```html
<div class="tabs">
<button class="tab-button" onclick="openTab('tab1')">Tab 1</button>
<button class="tab-button" onclick="openTab('tab2')">Tab 2</button>
<button class="tab-button" onclick="openTab('tab3')">Tab 3</button>
<div id="tab1" class="tab-content">
<p>Tab 1 content goes here.</p>
</div>
<div id="tab2" class="tab-content">
<p>Tab 2 content goes here.</p>
</div>
<div id="tab3" class="tab-content">
<p>Tab 3 content goes here.</p>
</div>
</div>
```
CSS 代码:
```css
.tabs {
display: flex;
flex-wrap: wrap;
margin-bottom: 1rem;
}
.tab-button {
background-color: #f5f5f5;
border: none;
border-bottom: 3px solid transparent;
color: #444;
cursor: pointer;
font-size: 1rem;
font-weight: bold;
padding: 0.5rem 1rem;
transition: border-bottom 0.2s ease-in-out;
}
.tab-button.active {
border-bottom-color: #007bff;
}
.tab-content {
display: none;
margin-top: 1rem;
}
.tab-content.active {
display: block;
}
```
JavaScript 代码:
```javascript
function openTab(tabName) {
// Hide all tab contents
const tabContents = document.querySelectorAll('.tab-content');
tabContents.forEach(tab => {
tab.classList.remove('active');
});
// Deactivate all tab buttons
const tabButtons = document.querySelectorAll('.tab-button');
tabButtons.forEach(button => {
button.classList.remove('active');
});
// Show the selected tab content and activate its button
const selectedTab = document.getElementById(tabName);
selectedTab.classList.add('active');
const selectedButton = document.querySelector(`[onclick="openTab('${tabName}')"]`);
selectedButton.classList.add('active');
}
```
以上代码实现了一个简单的 tab 切换效果,点击不同的 tab 按钮会显示对应的内容。