Vue滚动菜单锚点功能
话不多说 直接上代码了
1、HTML部分
2、js部分
mounted() {
let timeId;
window.addEventListener(
"scroll",
() => {
// 页面滚动停止100毫秒后才会执行下面的函数。
clearTimeout(timeId);
timeId = setTimeout(() => {
this.scrollToTop();
}, 100);
},
true
);
},
methods:{
//改变左边side栏
handleChangeLeftSide(index) {
this.selectedMenuId = index;
this.$el.querySelector(`#id${index}`).scrollIntoView({
behavior: "smooth", // 平滑过渡
block: "start", // 上边框与视窗顶部平齐。默认值
});
this.listBoxState = false; //在data中定义一个初始化值true
let timeId;
clearTimeout(timeId);
timeId = setTimeout(() => {
this.listBoxState = true;
}, 1000);
},
//滚动右侧事件
scrollToTop() {
var domHight = document.body.offsetHeight;
// dom滚动位置
// var scrollTop =
let scrollTop = this.$refs.content.scrollTop;
// window.pageYOffset ||
// document.documentElement.scrollTop ||
// document.body.scrollTop;
if (this.listBoxState) {
//productCateforyList是右侧数据
this.productCateforyList.forEach((v, i) => {
// 获取监听元素距离视窗顶部距离
var offsetTop = document.getElementById(`id${i}`).offsetTop;
// 获取监听元素本身高度
var scrollHeight = document.getElementById(`id${i}`).scrollHeight;
// 如果 dom滚动位置 >= 元素距离视窗距离 && dom滚动位置 <= 元素距离视窗距离+元素本身高度
// 则表示页面已经滚动到可视区了。
if (scrollTop >= offsetTop && scrollTop <= offsetTop + scrollHeight) {
// 导航栏背景色选中
this.selectedMenuId = i;
}
});
}
},
}