- 滚动锚点基于inView这个库,元素进入或者离开的时候会触发事件
- 点击锚点基于scrollTo,其实也可以用scrollInView这个API但是可能位置有所偏移导致导航的位置不准确。
1.in-view安装
GitHub - camwiegert/in-view: Get notified when a DOM element enters or exits the viewport. :eyes:
2.in-view挂载(main.js中挂载,后期用this点出来)
import InView from 'in-view'
Vue.prototype.inView = InView
3.滚动时逻辑处理
//inView.threshold(<阈值>) ,,默认是个0,监听元素进出不太准确
this.inView.threshold(0.5);
//多个锚点监听
this.componentsList.forEach((item, index) => {
// 元素如果进入到视口则触发
this.inView(".litem" + index).on('enter', (e) => {
//你自己的一些逻辑 this.isGo 是否已点击
if (!_self.isshownews && !this.isGo) {
this.active = index;
}
});
})
4.点击锚点时触发 逻辑就是点击时设置高亮哪个,跳转到那个元素的位置
go(index) {
this.isshownews = false
this.active = index;
//已经点击
this.isGo = true
let target = this.$refs['litem' + index][0]
// 核心点
this.$nextTick(item => {
if (index == 0) {
scrollTo(0, 0)
} else {
scrollTo(0, target.offsetTop + this.offsetTop)
}
})
},
5.滚动与点击冲突解决(点击时会触发滚动,这样会有点冲突)
window.addEventListener('scroll', function () { // 监听滚动事件
clearTimeout(scrollTimer);
scrollTimer = setTimeout(() => {
//点击滚动完成
that.isGo = false
}, 400);
});