1.vue 点击页面定位到指定位置 锚点跳转方法
html部分:
<template>
<div class="home">
<div class="head" :style="{height:liHeight+'px'}" style="background:#e2c08d; transition: height 0.3s;">
<li v-for="(item,index) in arr" v-show="index<liIndex" @click="liChange(index)">{{item}}</li>
</div>
<div id="li0" style="height:500px; background:pink;">我是第一个盒子</div>
<div id="li1" style="height:500px; background:skyblue;">我是第二个盒子</div>
<div id="li2" style="height:500px; background:#57643b;">我是第三个盒子</div>
<div id="li3" style="height:500px; background:#caa062;">我是第四个盒子</div>
<div id="li4" style="height:500px; background:#cb1c2d;">我是第五个盒子</div>
</div>
</template>
js部分:
<script>
export default {
data() {
return {
arr:['跳到第一个盒子','跳到第二个盒子','跳到第三个盒子','跳到第四个盒子','跳到第五个盒子'],
flag:false,
liHeight:30,
liIndex:1,
}
},
methods: {
//瞄点定位事件
liChange(i){
this.$nextTick(function(){
if(i==0&&this.flag==false){
this.flag=true;
this.liHeight=150;
this.liIndex=10
}else if(i==0){
this.flag=false,
this.liIndex=1;
this.liHeight=30
}else{ //瞄点定位
document.querySelector('#li'+i).scrollIntoView({
behavior: "smooth",//其中behavior表示为过渡方式,值有auto和smooth两种,auto表示立即定位到目标元素,smooth表示平滑移动到目标元素,默认为auto
block: "start", //block表示目标元素出现在屏幕的位置,值有end,center,start三种。
inline: "nearest"
});
}
})
}
}
}
</script>
此处的$nextTick方法意思是在下次DOM更新循环结束之后执行延迟回调。
锚点定位的主要用到 document.querySelector( '#id名/.类名 ' ).scrollIntoView(true) 方法。
2.uniapp实现锚点定位
在这里我就不上html的代码了,直接上逻辑,你们直接拿走使用就可以实现啦
uni.createSelectorQuery().select('#li'+i).boundingClientRect(data=>{//目标位置的节点:类class或者id
uni.createSelectorQuery().select(".home").boundingClientRect(res=>{//最外层盒子的节点:类class或者id
uni.pageScrollTo({
duration: 1000, //过渡时间
scrollTop:data.top-50 - res.top,//到达距离顶部的top值 根据自己情况可调
//scrollTop:data.top - res.top,//如果置顶
})
}).exec()
}).exec();