前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >锚点导航

锚点导航

作者头像
wade
发布2021-01-12 14:46:12
2.7K0
发布2021-01-12 14:46:12
举报
文章被收录于专栏:coding个人笔记

锚点导航这种功能应该很常见,早之前就分享过移动端移动端导航简单实现,配合起来就很容易实现可移动的锚点导航,而且不是用hash模式。当然,PC端也能直接用。

先上效果:

为了方便直接用vue语法,首先要给每一个块一个唯一的ref,然后初始化的时候记录每一个块距离顶部的距离和每一个块的高度,并监听滚动:

代码语言:javascript
复制
this.$nextTick(() => {
  this.firstOffsetTop = this.$refs[this.currentKey][0].offsetTop;
  document.addEventListener('scroll', this.onScroll);
  this.list.forEach((val) => {
    this.itemOffsetTop.push({
      key: val.key,
      num: this.$refs[val.key][0].offsetTop - this.firstOffsetTop,
      height: this.$refs[val.key][0].clientHeight
    });
  });
});

最重要的三个方法:

代码语言:javascript
复制
onScroll(){
  const scrollTop = document.documentElement.scrollTop;
  this.itemOffsetTop.forEach((val, index) => {
    if(scrollTop > val.num && scrollTop - val.num > val.height / 2){
      if(index == this.itemOffsetTop.length - 1){
        this.currentKey = this.itemOffsetTop[index].key;
      }else {
        this.currentKey = this.itemOffsetTop[index + 1].key;
      }
    }else if(scrollTop < this.itemOffsetTop[0].height / 2){
      this.currentKey = this.itemOffsetTop[0].key;
    }
  })
},
//点击锚点定位
changeKey(key){
  document.removeEventListener('scroll', this.throttledScrollHandler);
  this.currentKey = key;
  let to = this.$refs[key][0].offsetTop - this.firstOffsetTop;
  this.animationScrollTo(document.documentElement, to);
},
//锚点定位动画滚动
animationScrollTo(el, to) {
  let scrollY = 0;
  const beginY = el.scrollTop;
  const raf = window.requestAnimationFrame || (func => setTimeout(func, 10));
  const moveFn = () => {
    if (beginY - to < 0) {
      scrollY += (to - beginY) / 30;
      if(scrollY <= (to - beginY)){
        el.scrollTop = beginY + scrollY;
        raf(moveFn);
      }else {
        el.scrollTop = to;
        document.addEventListener('scroll', this.throttledScrollHandler);
      }
    }else if(beginY - to > 0){
      scrollY += (beginY - to) / 30;
      if(scrollY <= (beginY - to)){
        el.scrollTop = beginY - scrollY;
        raf(moveFn);
      }else {
        el.scrollTop = to;
        document.addEventListener('scroll', this.throttledScrollHandler);
      }
    }
  };
  raf(moveFn);
}

先判断上滑还是下滑,每次滑动距离除以30,当作滑动的速度,这边注意一点,如果滑动距离为0的情况下是要处理的,否则滚动条会卡住,之前就是一个变量判断是否大于0,结果滚动条卡住了。滚动加点动画效果直接用requestAnimationFrame ,一般都兼容,如果不兼容就用定时器,定时器会比较不顺滑。

监听滚动计算滚动的距离是否大于记录的距离,且超过一半就算下一个,菜单上面定位到下一个。

完整demo,自己引入vue:

https://github.com/wade3po/demoCode/blob/main/%E9%94%9A%E7%82%B9%E5%AF%BC%E8%88%AA.html

(完)

Coding 个人笔记

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-01-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 coding个人笔记 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档