新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

js实现选项卡,js实现选项卡切换

发布时间:2023-09-15 12:30:26

js实现选项卡

以下是一个简单的 JS 实现选项卡的例子:
HTML 代码:
```html






选项卡 1 内容


这是选项卡 1 的内容。




选项卡 2 内容


这是选项卡 2 的内容。




选项卡 3 内容


这是选项卡 3 的内容。




```
CSS 代码:
```css
.tab-container {
max-width: 600px;
margin: 0 auto;
}
.tab {
background-color: #f1f1f1;
border: none;
color: black;
padding: 10px 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 4px 4px 0 0;
cursor: pointer;
}
.tab:hover {
background-color: #ddd;
}
.tab-content {
display: none;
padding: 20px;
border: 1px solid #ddd;
border-top: none;
}
.tab-content h3 {
margin-top: 0;
}
.tab-content p {
margin-bottom: 0;
}
```
JS 代码:
```javascript
function openTab(event, tabId) {
// 获得所有的选项卡按钮和内容
var tabButtons = document.getElementsByClassName('tab');
var tabContents = document.getElementsByClassName('tab-content');
// 隐藏所有的选项卡内容
for (var i = 0; i < tabContents.length; i++) {
tabContents[i].style.display = 'none';
}
// 重置所有选项卡按钮的样式
for (var i = 0; i < tabButtons.length; i++) {
tabButtons[i].className = tabButtons[i].className.replace(' active', '');
}
// 显示当前选项卡内容
document.getElementById(tabId).style.display = 'block';
// 添加 active 类到当前选项卡按钮
event.currentTarget.className += ' active';
}
```
这个例子中,我们使用了一个 `openTab` 函数来控制选项卡的切换。当用户点击选项卡按钮时,会调用这个函数,并传递事件对象和选项卡的 ID。函数会首先隐藏所有的选项卡内容,然后显示当前选项卡的内容。同时,它还会重置所有选项卡按钮的样式,并为当前选项卡按钮添加 active 类,以突出显示当前选项卡。
最后,我们使用 CSS 来设置选项卡和选项卡内容的样式。
你可以将以上代码复制到一个 HTML 文件中并在浏览器中运行,以查看效果。