1、vue开发,在mouted生命周期监听页面滚动的方法
window.addEventListener('scroll',this.onScroll,true)
2、页面销毁时,卸载这个方法destroyed
window.removeEventListener('scroll', this.onScroll,true)
3、定义一个list数组,
navList: Object.freeze([{
name: '模块一',
ref: 'one'
}, {
name: '模块二',
ref: 'two'
}, {
name: '模块三',
ref: 'three'
}, {
name: '模块四',
ref: 'four'
}, {
name: '模块五',
ref: 'five'
}]),
navCheck:null,
4、
// 滚动条,滚动到相应的模块,对应的标题展示
onScroll() {
const scrollTop = Math.abs(document.documentElement.getBoundingClientRect().top)
const one = this.$refs.one.$el.offsetTop - 330
const two = this.$refs.two.$el.offsetTop - 80
const three = this.$refs.three.$el.offsetTop - 80
const four = this.$refs.four.$el.offsetTop - 80
const five = this.$refs.five.$el.offsetTop - 200
if (scrollTop < one) {
this.navCheck = null
} else if (scrollTop > one && scrollTop < two) {
const {top} = this.$refs.hotCast.$el.getBoundingClientRect()
if (top > -50 && top <= 400) {
this.navCheck = 'one'
}
} else if (scrollTop > two && scrollTop < three) {
const {top} = this.$refs.hotIndustry.$el.getBoundingClientRect()
if (top > -50 && top <= 200) {
this.navCheck = 'two'
}
} else if (scrollTop > three && scrollTop < four) {
const {top} = this.$refs.hotEnterprise.$el.getBoundingClientRect()
if (top > -50 && top <= 100) {
this.navCheck = 'three'
}
} else if (scrollTop > four && scrollTop < five) {
const {top} = this.$refs.youthSink.$el.getBoundingClientRect()
if (top > -50 && top <= 100) {
this.navCheck = 'four'
}
} else if (scrollTop > five) {
this.navCheck = 'five'
}
},
// 点击侧边栏的标题,滚动条滚动到响应的位置
scrollTo(){
let element = null
element = this.$refs[ref].$el
element && element.scrollIntoView({behavior: 'smooth'})
}
5、在html写上
<ul>
<li
v-for="(item,index)" in navList :key="index"
:class="[navCheck === item.ref && 'navCheck']"
>{{item.name}}</li>
</ul>
可以对navCheck,设置css样式