这里声明一下,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) {
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);
}
}
}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);
}
}
}
},
学废了点个赞呗!
|