Tab选项卡(Tabbed Interface)是一种常见的用户界面设计模式,它允许用户通过点击不同的标签页来切换显示不同的内容区域。这种设计模式可以提高界面的组织性和用户的操作效率,因为它将相关信息分组并在有限的空间内展示。
<div class="tabs">
<button class="tab-button active" data-tab="tab1">Tab 1</button>
<button class="tab-button" data-tab="tab2">Tab 2</button>
<button class="tab-button" data-tab="tab3">Tab 3</button>
<div class="tab-content active" id="tab1">
<h2>Content for Tab 1</h2>
<p>This is the content for tab 1.</p>
</div>
<div class="tab-content" id="tab2">
<h2>Content for Tab 2</h2>
<p>This is the content for tab 2.</p>
</div>
<div class="tab-content" id="tab3">
<h2>Content for Tab 3</h2>
<p>This is the content for tab 3.</p>
</div>
</div>
.tabs {
display: flex;
flex-direction: column;
}
.tab-button {
padding: 10px;
cursor: pointer;
background-color: #f1f1f1;
border: none;
outline: none;
transition: background-color 0.3s;
}
.tab-button.active {
background-color: #ddd;
}
.tab-content {
display: none;
padding: 20px;
border: 1px solid #ddd;
}
.tab-content.active {
display: block;
}
document.addEventListener('DOMContentLoaded', function() {
const tabButtons = document.querySelectorAll('.tab-button');
const tabContents = document.querySelectorAll('.tab-content');
tabButtons.forEach(button => {
button.addEventListener('click', function() {
const targetTab = this.getAttribute('data-tab');
// Remove active class from all buttons and contents
tabButtons.forEach(btn => btn.classList.remove('active'));
tabContents.forEach(content => content.classList.remove('active'));
// Add active class to the clicked button and corresponding content
this.classList.add('active');
document.getElementById(targetTab).classList.add('active');
});
});
});
data-tab
属性值与内容面板的id
匹配。.active
类应用到正确的元素上。通过以上示例和解释,你应该能够实现一个基本的Tab选项卡功能,并根据需要进行扩展和调整。
领取专属 10元无门槛券
手把手带您无忧上云