vue、uniapp实现锚点定位

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();

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值