参考链接:vue监听页面中的某个div的滚动事件,并判断滚动的位置 - 翀上云霄 - 博客园 (cnblogs.com)
循环目录下绑定类:
:class="{ 'active': menuActive === index }"
定义.active类的样式。
监听滚动事件,进行下一步操作。
window.addEventListener('scroll',this.handleScroll)
对滚动事件进行处理。
handleScroll(){
const scrollTop = document.documentElement.scrollTop; //获取dom滚动距离
const offsetHeight = document.documentElement.offsetHeight; //获取可视区高度
const scrollHeight = this.$refs.tiBox.scrollHeight; //获取滚动条总高度
for(let i = 1;i<16;i++){ //16是循环的个数
//offsetTop: 获取当前元素到其定位父级(offsetParent)的顶部距离
let offset_before = this.$el.querySelector('#anchor'+i).offsetTop;
let offset_after = this.$el.querySelector('#anchor'+(i+1)).offsetTop;
if (scrollTop >= offset_before && scrollTop < offset_after) {
//判断是否滚动到了底部
if (scrollTop + offsetHeight >= scrollHeight) {
// 把距离顶部的距离加上可视区域的高度 等于或者大于滚动条的总高度就是到达底部
if (this.menuActive < i) {
this.menuActive = i;
}
} else {
this.menuActive = i;
}
break;
}
}
},
参考链接:vue监听页面中的某个div的滚动事件,并判断滚动的位置 - 翀上云霄 - 博客园 (cnblogs.com)