1、这个方法有个不好的地方就是要自己算每个盒子要滑动的高度,下面是结构
<ul>
<li class="liTem" :class="{ acver: currentTab === 'tab1' }" @click="scrollToTab('tab1')">首页</li>
<li class="liTem" :class="{ acver: currentTab === 'tab2' }" @click="scrollToTab('tab2')">服务内容</li>
<li class="liTem" :class="{ acver: currentTab === 'tab3' }" @click="scrollToTab('tab3')">业务案例</li>
<li class="liTem" :class="{ acver: currentTab === 'tab4' }" @click="scrollToTab('tab4')">关于我们</li>
<li class="liTem" :class="{ acver: currentTab === 'tab5' }" @click="scrollToTab('tab5')">联系方式</li>
</ul>
<div class="section1 " id="section1">Section 1</div>
<div class="section2 " id="section2">Section 2</div>
<div class="section3 " id="section3">Section 3</div>
2、简单写点css
.tabsul {
position: fixed;
top: 0;
left: 0;
width: 100%;
background-color: #f0f0f0;
display: flex;
justify-content: center;
z-index: 1000;
}
.liTem {
padding: 0 0px 5px 0px;
box-sizing: border-box;
height: 35px;
text-align: center;
font-size: 16px;
font-weight: 500;
margin: 0 20px;
cursor: pointer;
}
.section {
display: flex;
justify-content: center;
font-size: 24px;
color: #fff;
border: 1px solid #ccc;
}
.section1{
height: 430px;
background: #48a994;
}
.section2{
height: 1200px;
background: #49396f;
}
.section3{
height: 600px;
background: #349f64;
}
.section4{
height: 1200px;
background: #9c7d39;
}
.acver {
font-size: 16px;
font-weight: 500;
border-bottom: 3px #ff8000 solid;
}
3、在data里声明这些变量
currentTab: "tab1",
tabScrollPositions: {
// 每个tab对应的滚动位置
tab1: 0,
tab2: 670,
tab3: 1700,
// tab4: 4360,
tab4: 3760,
tab5: 5015,
},
4、这里写点击事件
mounted() {
window.addEventListener("scroll", this.handleScroll);
},
beforeDestroy() {
window.removeEventListener("scroll", this.handleScroll);
},
methods: {
scrollToTab(tab) {
this.currentTab = tab;
const position = this.tabScrollPositions[tab];
window.scrollTo({
top: position,
behavior: "smooth",
});
},
handleScroll() {
const scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
for (const tab in this.tabScrollPositions) {
if (
scrollTop >= this.tabScrollPositions[tab] - 50 &&
scrollTop < this.tabScrollPositions[tab] + 50
) {
// 假设50是阈值
this.currentTab = tab;
break;
}
}
},
}