如何用HTML+CSS编写灵活的Tab页
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flexible Tab Page (2)</title>
<style>
.tabs {
display: flex;
justify-content: space-between;
background-color: #f2f2f2;
padding: 10px;
}
.tab {
padding: 10px;
cursor: pointer;
user-select: none;
}
.tab.active {
background-color: #ccc;
}
.content {
border: 1px solid #ccc;
border-top: none;
padding: 20px;
}
</style>
</head>
<body>
<div class="tabs">
<div class="tab active">Tab 1</div>
<div class="tab">Tab 2</div>
<div class="tab">Tab 3</div>
</div>
<div class="content">Content for Tab 1</div>
<script>
document.querySelectorAll('.tab').forEach(tab => {
tab.addEventListener('click', () => {
// Remove active class from all tabs
document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
// Add active class to the clicked tab
tab.classList.add('active');
// Get the name of the tab
const tabName = tab.textContent.trim();
// Show the content for the active tab
document.querySelectorAll('.content').forEach(content => {
if(content.textContent.trim() === `Content for ${tabName}`) {
content.style.display = 'block';
} else {
content.style.display = 'none';
}
});
});
});
</script>
</body>
</html>
这段代码使用了原生JavaScript来处理点击事件,当用户点击标签时,会更改标签的样式并显示对应的内容区域。这个例子简单直观,方便理解和学习。
评论已关闭