javascript实现tab切换
时间: 2023-06-18 16:04:50 浏览: 108
HTML 结构:
```html
<div class="tab-container">
<ul class="tab-nav">
<li class="active">Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
</ul>
<div class="tab-content">
<div class="tab-panel active">Tab 1 content</div>
<div class="tab-panel">Tab 2 content</div>
<div class="tab-panel">Tab 3 content</div>
</div>
</div>
```
CSS 样式:
```css
.tab-nav {
display: flex;
list-style: none;
margin: 0;
padding: 0;
}
.tab-nav li {
cursor: pointer;
margin-right: 10px;
padding: 10px;
border: 1px solid #ccc;
}
.tab-nav li.active {
background-color: #ccc;
}
.tab-content .tab-panel {
display: none;
padding: 10px;
}
.tab-content .tab-panel.active {
display: block;
}
```
JavaScript 实现:
```javascript
const tabNav = document.querySelector('.tab-nav');
const tabPanels = document.querySelectorAll('.tab-panel');
tabNav.addEventListener('click', (event) => {
const target = event.target;
if (target.tagName.toLowerCase() === 'li') {
const index = Array.prototype.indexOf.call(tabNav.children, target);
if (index >= 0) {
// 切换选中状态
for (let i = 0; i < tabNav.children.length; i++) {
tabNav.children[i].classList.remove('active');
tabPanels[i].classList.remove('active');
}
target.classList.add('active');
tabPanels[index].classList.add('active');
}
}
});
```
以上代码实现了一个简单的 Tab 切换效果。当点击 Tab 标签时,会切换对应面板的显示。
阅读全文