vue实现头部吸顶描点
效果:页面滚到具体位置时,顶部吸附(粘性定位),点击描点跳转到对应位置,滚到到对应位置描点自动切换。
html:使用elment ui,name对应每个位置的ref名称,
<el-tabs @tab-click="jump" v-model="tabActive">
<el-tab-pane label="基础信息" name="base" ></el-tab-pane>
<el-tab-pane label="经营信息" name="manage"></el-tab-pane>
<el-tab-pane
label="老板及对接人信息"
name="boss"
></el-tab-pane>
<el-tab-pane label="其它信息" name="other"></el-tab-pane>
</el-tabs>
举例:基础信息ref:
点击描点跳转具体位置方法:
jump(e) {
// 当前窗口正中心位置到指定dom位置的距离
//页面滚动了的距离
let height =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop;
//指定dom到页面顶端的距离
let dom = this.$refs[e.name];
let domHeight = dom.offsetTop + 60;
//滚动距离计算
var S = Number(height) - Number(domHeight);
//判断上滚还是下滚
if (S < 0) {
//下滚
S = Math.abs(S);
window.scrollBy({ top: S, behavior: "smooth" });
this.$refs.nav.style.position = 'fixed'
this.$refs.nav.style.top = '0px'
} else if (S == 0) {
//不滚
window.scrollBy({ top: 0, behavior: "smooth" });
} else {
//上滚
S = -S;
window.scrollBy({ top: S, behavior: "smooth" });
}
滚到到对应位置描点自动切换方法:
mouted中添加监听滚动事件:
//给window添加一个滚动滚动监听事件
window.addEventListener('scroll', this.handleScroll)
具体方法
handleScroll(){
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
console.log(scrollTop)
if(scrollTop>170){
this.$refs.nav.style.position = 'fixed'
this.$refs.nav.style.top = '0px'
if(scrollTop>170 && scrollTop<this.$refs['manage'].offsetTop){
this.tabActive = 'base'
}
else if(scrollTop>this.$refs['manage'].offsetTop && scrollTop<this.$refs['boss'].offsetTop){
this.tabActive = 'manage'
}
else if(scrollTop>this.$refs['boss'].offsetTop && scrollTop<this.$refs['other'].offsetTop-500){
this.tabActive = 'boss'
}
else if(scrollTop>this.$refs['other'].offsetTop-500 ){
this.tabActive = 'other'
}
}
else{
this.$refs.nav.style.position = ''
}
}