实现tab栏跟随内容出现,添加激活样式,支持点击切换,支持滚动切换
js部分
//tab栏信息
const activeTab = ref("1");
const tabs = reactive([
{ value: "section1", label: "招聘信息", isActive: true },
{ value: "section2", label: "商务合作", isActive: false },
]);
//点击时切换
const modelValue = ref();
const changeTab = (val) => {
modelValue.value = val;
};
// 导航点击
const scrollToSection = (sectionId) => {
const section = document.getElementById(sectionId);
if (section) {
const scrollTop = section.offsetTop - 120;
window.scrollTo({
top: scrollTop,
behavior: "smooth",
});
}
};
//根据滚动切换
onMounted(() => {
window.onscroll = function () {
findCurrentTab();
};
});
onUnmounted(() => {
window.onscroll = null; // 取消滚动事件监听
});
const findCurrentTab = () => {
const sectionCon = document.querySelectorAll(".content");
sectionCon.forEach(function (el, idx) {
var t = el.getBoundingClientRect().top;
var b = el.getBoundingClientRect().bottom;
// console.log(t, b);
if (t <= 200 && b > 200) {
tabs[idx].isActive = true;
modelValue.value = idx;
} else {
tabs[idx].isActive = false;
}
});
};
html部分
//导航栏
<div
class="flex"
:class="{'business-active': modelValue === index || item.isActive === true,}"
v-for="(item, index) in tabs"
:key="item.value"
@click="changeTab(index), scrollToSection(item.value)"
>
<div class="left-label">{{ item.label }}</div>
</div>
//内容
<div id="section1" class="content"></div>
<div id="section2" class="content"></div>