分享一段Tab切换源码(HTML)
每个选项都对应着不同的内容显示区域,默认显示全部(第一个)页面
HTML
<div class="tabs">
<button class="tab-link active" data-tab-target="#all">全部</button>
<button class="tab-link" data-tab-target="#selected">精选</button>
<button class="tab-link" data-tab-target="#articles">文章</button>
<button class="tab-link" data-tab-target="#code-share">源码分享</button>
</div>
<div class="tab-content active" id="all"></div>
<div class="tab-content" id="selected"></div>
<div class="tab-content" id="articles"></div>
<div class="tab-content" id="code-share"></div>
CSS
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
.navbar-fixed {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100px;
background: #fff;
display: flex;
justify-content: center;
align-items: center;
z-index: 100;
overflow: hidden;
}
#logoImg {
width: 100%;
height: auto;
}
.tabs {
display: flex;
margin-top: 100px;
}
.tab-link {
flex: 1;
position: relative;
padding: 0.5rem;
cursor: pointer;
outline: none;
border: none;
background: transparent;
color: #333;
transition: color 0.3s;
-webkit-tap-highlight-color: transparent; /* 移除点击时的高亮效果 */
}
.tab-link::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
width: 0;
height: 2px;
background: #ff5733;
transition: width 0.3s ease;
}
.tab-link.active::after {
width: 100%;
}
.tab-content {
display: none;
padding: 2em;
}
.tab-content.active {
display: block;
}
@media (max-width: 600px) {
.tabs {
flex-wrap: wrap;
}
}
JavaScript
document.addEventListener("DOMContentLoaded", function () {
const tabLinks = document.querySelectorAll('.tab-link');
const tabContents = document.querySelectorAll('.tab-content');
let lastActiveTab = null;
function activateTab(targetId) {
tabContents.forEach(content => content.classList.remove('active'));
tabLinks.forEach(link => link.classList.remove('active'));
const targetContent = document.querySelector(targetId);
const targetLink = document.querySelector(`[data-tab-target="${targetId}"]`);
targetContent.classList.add('active');
targetLink.classList.add('active');
const afterElement = targetLink.querySelector('::after');
if (lastActiveTab) {
const direction = targetLink.offsetLeft > lastActiveTab.offsetLeft ? 'right' : 'left';
afterElement.style.transition = `width 0.3s ease, transform 0.3s ease`;
afterElement.style.transform = `translateX(${direction === 'right' ? 100 : -100}%)`;
setTimeout(() => {
afterElement.style.transform = '';
}, 300);
}
lastActiveTab = targetLink;
}
tabLinks.forEach(link => {
link.addEventListener('click', function(e) {
e.preventDefault();
const target = this.getAttribute('data-tab-target');
activateTab(target);
});
});
activateTab('#home'); // 默认激活第一个选项卡
});