这里声明一下,a标签锚点跳转和本文跳转不冲突,如果不需要平滑效果,只需要点击跳转锚点连接看此文;:vue实现锚点定位跳转,a标签实现锚点定位跳转
先看看最终效果图:
js锚点跳转添加过度动画,id锚点跳转js添加平滑过度效果
接下来看代码:我的导航栏是动态的,内容列表也是循环出来的,其实道理都一样,基本原理就是找到跳转目标元素距离顶部的距离(document.getElementById(‘#type’)).offsetTop),然后获取当前距离顶部距离(document.documentElement.scrollTop),然后用js进行上下滑动操作,接下来看代码,为了看了简介,我删掉了不相关代码:
HTML
<!-- 右侧悬浮导航栏 -->
<div>
<div v-for="(item, indext) in fixList" :key="indext">
<div
@click="tapItem(indext)"
>
{{ item.name}}
</div>
</div>
<div>顶部</div>
</div>
<!-- 商品分组显示页,也就是跳转的目标页 -->
<div
v-for="(item, index) in fixList"
:key="index"
:name="'type-' + index"
:id="'type-' + index"
>
内容区域,视频中的商品列表区....
</div>
JS
tapItem(index) {
// 点击单个分类,跳转到相应的锚点连接,并添加过度动画平滑效果
this.activeBtn = index;
// 需要跳转的目标锚点所在高度,因为定位不准确,应该是以底部为跳转距离了,我这里添加了一个屏幕高度,跳转位置刚好正确,根据项目自己修改
let jumpHeight = (document.getElementById('type-' + index)).offsetTop + (document.documentElement.clientHeight - 90);
// 当前位置距离顶部的高度
let top = document.documentElement.scrollTop
if(jumpHeight > top) {
// 目标高度大于当前高度,说明需要往下滑
let heigth = jumpHeight - top;
if (this.myTimer == -1) { // 这个是一个定时器,用来防止重复点击的
//滑动高度大于10000,在0.8秒内完成平移动画,80可以自己根据实际情况来改就是0.8秒
if (heigth > 10000) {
let num = Number((heigth / 80).toFixed(0));
this.myTimer = setInterval(() => {
top += num;
if (top >= jumpHeight) {
top = jumpHeight;
window.clearInterval(this.myTimer);
this.myTimer = -1;
}
window.scrollTo(0, top);
}, 10);
} else {
// 滑动距离小于10000,按默认速度滑动
this.myTimer = setInterval(() => {
top += 80;
if (top >= jumpHeight) {
top = jumpHeight;
window.clearInterval(this.myTimer);
this.myTimer = -1;
}
window.scrollTo(0, top);
}, 10);
}
}
}else { // 目标高度小于当前高度,说明需要往上滑
let heigth = top - jumpHeight;
if (this.myTimer == -1) {
if (heigth > 10000) {
let num = Number((heigth / 80).toFixed(0));
this.myTimer = setInterval(() => {
top -= num;
if (top <= jumpHeight) {
top = jumpHeight;
window.clearInterval(this.myTimer);
this.myTimer = -1;
}
window.scrollTo(0, top);
}, 10);
} else {
this.myTimer = setInterval(() => {
top -= 80;
if (top <= jumpHeight) {
top = jumpHeight;
window.clearInterval(this.myTimer);
this.myTimer = -1;
}
window.scrollTo(0, top);
}, 10);
}
}
}
},
学废了点个赞呗!