export default {
data() {
return {
activeMenu: 0,
scrollBox: '',
jumpFlag: false,
fixTop: false
}
},
mounted() {
this.scrollBox = document.getElementById('scrollBox')
window.addEventListener('scroll', ()=> {
let scrollTop =
document.documentElement.scrollTop ||
document.body.scrollTop ||
window.pageYOffset
if (scrollTop > this.scrollBox.offsetTop) {
this.fixTop = true
} else {
this.fixTop = false
}
if (!this.jumpFlag) {
let jumpDom = document.querySelectorAll('.item-section')
jumpDom.forEach((item, index) => {
if (item.offsetTop {
this.jumpFlag = false
}, 5000)
}
}
}
另vue实现锚点跳转之scrollIntoView()方法
滚动到某个特定元素 :scrollIntoView();这个方法不用获取距页面顶部的高度,啥都不用,有id或者class就行啦,几乎可以满足你锚点跳转的所有需求,对齐方式,以及平滑滚动了
这里是v-for循环出来需要点击跳转到对应div的事件
v-for="(value,index) in data" @click="scrollToPosition(index)">{{...}}
这就是你点击scrollToPosition事件需要滚动对应的div
v-for="(value,index) in data" class="roll">{{...}}
js部分
methods:{
scrollToPosition(index){
document.getElementsByClassName('roll')[index].scrollIntoView()
}
这样就利用scrollIntoView()简单实现了一个锚点跳转,下边来看一个scrollIntoView中的一些属性
scrollIntoView(true)相等于scrollIntoView();元素的顶端将和其所在滚动区的可视区域的顶端对齐
为true时相应的 scrollIntoViewOptions: {block: “start”, inline: “nearest”}。
这是这个参数的默认值。
scrollIntoView(false)元素的底端将和其所在滚动区的可视区域的底端对齐
为false时相应的scrollIntoViewOptions: {block: “end”, inline: “nearest”}。
同时他的参数也可以是一个object对象
scrollIntoView({
behavior:auto //定义动画过渡效果"auto"或 "smooth" 之一。默认为 "auto"。
block:start//定义垂直方向的对齐, "start", "center", "end", 或 "nearest"之 一。
默认为 "start"。
inline:nearest//"start", "center", "end", 或 "nearest"之一。默认为 "nearest"。
})
其中smooth是平滑滚动 start和end是目标滚动到的位置
注意:兼容性的问题多数主流浏览器已经支持其基本功能,也就是说,使用true,false两个参数,来实现木讷的定位(没有滚动动画)是没有任何问题的,但是传入object参数时,就不得不说一句,IE各种版本会直接忽略,全部看成true参数属性,如果想看到滚动动画,就只有火狐和chrome