用js写一个Tap栏切换效果
时间: 2024-01-04 21:03:12 浏览: 100
好的,以下是一个简单的用 JavaScript 实现 Tap 栏切换效果的示例代码:
HTML 结构:
```html
<div class="tab-wrapper">
<div class="tab-menu">
<button class="active">Tab 1</button>
<button>Tab 2</button>
<button>Tab 3</button>
</div>
<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-wrapper {
display: flex;
flex-direction: column;
align-items: center;
}
.tab-menu {
display: flex;
justify-content: center;
}
.tab-menu button {
padding: 10px 20px;
margin: 0 10px;
border: none;
border-bottom: 2px solid #ccc;
background-color: transparent;
cursor: pointer;
}
.tab-menu button.active {
border-bottom-color: #333;
}
.tab-content .tab-panel {
display: none;
padding: 20px;
}
.tab-content .tab-panel.active {
display: block;
}
```
JavaScript 代码:
```javascript
// 获取元素
const tabMenu = document.querySelector('.tab-menu');
const tabButtons = document.querySelectorAll('.tab-menu button');
const tabContent = document.querySelector('.tab-content');
const tabPanels = document.querySelectorAll('.tab-panel');
// 绑定按钮点击事件
tabMenu.addEventListener('click', event => {
const target = event.target;
if (target.tagName === 'BUTTON') {
// 切换按钮状态
tabButtons.forEach(button => {
button.classList.remove('active');
});
target.classList.add('active');
// 切换面板内容
const targetIndex = Array.from(tabButtons).indexOf(target);
tabPanels.forEach(panel => {
panel.classList.remove('active');
});
tabPanels[targetIndex].classList.add('active');
}
});
```
以上示例代码实现了一个简单的 Tap 栏切换效果。点击 Tap 栏中的不同按钮会切换显示不同的面板内容。
阅读全文