页面代码 在这个totalM标签上我使用了粘性布局vant4
网址: Sticky 粘性布局 - Vant 4 (gitee.io)
<template>
<h1>这是楼层测试的页面</h1>
<div class="top"></div>
<div class="da">
<!-- 这是流程的目录 -->
<!-- 在这里使用了粘性布局 -->
<van-sticky>
<div class="totalM">
<div class="menu" @click="jump(0)" :class="[num == 0 ? 'sele' : '']">1</div>
<div class="menu" @click="jump(1)" :class="[num == 1 ? 'sele' : '']">2</div>
<div class="menu" @click="jump(2)" :class="[num == 2 ? 'sele' : '']">3</div>
<div class="menu" @click="jump(3)" :class="[num == 3 ? 'sele' : '']">4</div>
<div class="menu" @click="jump(4)" :class="[num == 4 ? 'sele' : '']">5</div>
</div>
</van-sticky>
<div class="ccc"></div>
<!-- 这是楼层的内容 -->
<div class="aa">
<div class="h-800" style="background:red;">
<h1>1</h1>
</div>
<div class="h-800" style="background:yellow;">
<h1>2</h1>
</div>
<div class="h-800" style="background:blue;">
<h1>3</h1>
</div>
<div class="h-800" style="background:black;">
<h1>4</h1>
</div>
<div class="h-800" style="background:pink;">
<h1>5</h1>
</div>
</div>
</div>
</template>
监听代码
import { ref,watch } from 'vue';
const num=ref(0)
watch(()=>{
var inner = document.getElementsByClassName('h-800');
// 注册滚动监听事件
window.onscroll = function () {
// 获取滚动条距离页面底部的距离
var tops = document.documentElement.scrollTop || document.body.scrollTop;
// console.log(tops)
//判断滚动的位置,从而改变楼层选项的样式
for (var i = 0; i < inner.length; i++) {
if (inner[i].offsetTop <= tops + 200 && tops <= inner[i].offsetTop) {
num.value = i
}
}
}
})
事件代码
const jump=(index)=> {
num.value = index
var body = document.getElementsByTagName('body')[0];
// 获取所有的楼层
var inner = document.getElementsByClassName('h-800');
console.log(body)
console.log(inner)
console.log(index)
console.log(inner[index].offsetTop)
window.scrollTo(0, inner[index].offsetTop)
// document.body.scrollTop=inner[index].offsetTop
console.log(body.scrollTop)
}
样式代码
<style lang="scss" scoped>
.top {
width: 100%;
height: 200px;
background-color: aqua;
}
.da {
display: flex;
.h-800 {
width: 250px;
height: 500px;
}
.ccc {
width: 200px;
}
.totalM {
position: fixed;
width: 125px;
height: 100px;
background: gray;
}
}
.sele {
background: white;
}
</style>
效果: