1、html
tabs
对应监听模块
<div class="scroll-item" ref="content2">1</div>
<div class="scroll-item" ref="content2">2</div>
<div class="scroll-item" ref="content2">3</div>
<div class="scroll-item" ref="content2">4</div>
2、js
mounted() {
document.onscroll = (e) => {
this.scrollNav(document.querySelectorAll('.scroll-item'));
};
},
//方法
methods:{
scrollNav(sections) {
const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; // 滚动条偏移量
sections.forEach((item, index) => {
if (item.offsetTop - 100 <= scrollTop) {
this.activeTabIndex = index; //根据这个index给固定tabs的item赋值
}
});
// 假设最后一个滚动内容高度不够时滚动条到底部默认亮显示最后一个tab
// 变量windowHeight是可视区的高度
const windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
// 变量scrollHeight是滚动条的总高度
const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
// 滚动条到底部的条件
if (scrollTop + windowHeight === scrollHeight) {
this.activeTab = this.navList[this.navList.length - 1];
}
},
}
3、点击tabs到对应位置可以使用
//tab值是scorll-item的ref值
this.$refs[tab].scrollIntoView({ block: 'start', behavior: 'smooth' });
粗略记录