vue实现锚点功能

主要分两步:
(1)点击tab滚动到相应的内容

  <div class="panel">
     <nav class="nav">
          <a
                v-for="(tab, index) in tabList"
                :key="index"
                href="javascript:void(0)"
                @click="jump(tab, index)"
                :class="['tabItem', { tabSelected: curTab == index }]"
                >{{ tab.name }}</a
              >
     </nav>
     <div class="scroll" @scroll="onScroll">
	       <div id="introduction" class="scroll_content">
	            <div class="app_name tab_title">a</div>
	        </div>
	        <div id="details" class="scroll_content">
	             <div class="app_name tab_title">b</div>
	         </div>
       <div>
  </div>
  
   
//跳转
//distance: 0, //滚动条距离滚动区域顶部的距离
//totalY: 0, //锚点元素距离其顶部的距离(待滚动的距离)
//step: 0,
//在某一块区域内滑动不是整个页面滑动:
    jump(tab, index) {
	      this.curTab = index;
	      let scrollItems = document.querySelectorAll(".scroll_content");
	      this.totalY = scrollItems[index].offsetTop - scrollItems[0].offsetTop;
	      this.distance = document.querySelector(".scroll").scrollTop;
	      this.step = this.totalY / 50;
	      if (this.totalY > this.distance) {
	      	  this.smoothDown(document.querySelector(".scroll"));
	      } else {
		        let newTotal = this.distance - this.totalY;
		        this.step = newTotal / 50;
		        this.smoothUp(document.querySelector(".scroll"));
	      }
    },
    // 参数element为滚动区域
    smoothDown(element) {
	      if (this.distance < this.totalY) {
	        this.distance += this.step;
	        element.scrollTop = this.distance;
	        setTimeout(this.smoothDown.bind(this, element), 2);
	      } else {
	        element.scrollTop = this.totalY;
	      }
    },
    // 参数element为滚动区域
    smoothUp(element) {
	      if (this.distance > this.totalY){
	       this.distance -= this.step;
	        element.scrollTop = this.distance;
	        setTimeout(this.smoothUp.bind(this, element), 2);
	      } else {
	        element.scrollTop = this.totalY;
	      }
    },

//如果是整个页面滑动的话,就不需要像上面那样写了,直接滑动就好了
  jump(tab,index){
     document.querySelector(tab.id).scrollIntoView({
        behavior:"smooth"
      })
  }

(2) 内容滑动选中相应的tab

   onScroll(e) {
      let scrollItems = document.querySelectorAll(".scroll_content");
      for (let i = scrollItems.length - 1; i >= 0; i--) {
        // 判断滚动条滚动距离是否大于当前滚动项可滚动距离
        let judge = e.target.scrollTop >=scrollItems[i].offsetTop - scrollItems[0].offsetTop;
        if (judge) {
          this.curTab = i;
          break;
        }
      }
    },

实现效果如下:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值