资讯专栏INFORMATION COLUMN

滚动到一定位置 悬浮在顶部

Rocko / 1994人阅读

摘要:玩游戏许愿主会场红包翻倍页面滚动处理逻辑获取锚点合集

main

.float-box

nav.clearfix(:class="{"float": floatNav}")
  li
    a(href="#p1") 玩游戏
  li
    a(href="#p2") 许愿
  li
    a(href="#p3") 主会场
  li
    a(href="#p4") 红包翻倍

#p1
section#s1

a.banner(href="")

#p2
section#s2

   a.banner(href="")

// 页面滚动处理逻辑

  bindScrollEvent() {
    const self = this;
    // 获取锚点合集
    const archors = $("nav li a");
    // const flagOffset = $("#main").offsetTop().top;
    
    const flagOffset = document.getElementById("main").offsetTop;
    let tops = [];
    let raf;

    (() => {
      tops = [];
      let _id;
      // archors.forEach((item, index) => {
      //   _id = item.getAttribute("href");
      //   tops.push($(_id).offsetTop - 10);
      // });
      $("nav li a").each(function(i,v){
        _id = v.getAttribute("href");
        tops.push($(_id).offset().top - 10);
      });
    })();

    (() => {
      const part = location.hash;
      if (part && $(part)) {
        // console.log(window.scrollTop || document.body.scrollTop);
        setTimeout(function() {
          window.scrollTo(0, $(part).offset().top);
        }, 10);
      }
    })();

    const onscroll = () => {
      const st = window.scrollTop || document.body.scrollTop;
      let part;

      // console.log(st,flagOffset);

      if (st > flagOffset) {
        self.floatNav = true;
      } else {
        self.floatNav = false;
      }

      tops.forEach((item, index) => {
        if (st >= item) {
          if (!tops[index + 1]) {
            part = tops.length - 1;
          } else if (st <= tops[index + 1]) {
            part = index;
          }
        } else if (st < item) {
          if (!tops[index - 1]) {
            part = 0;
          } else if (st >= tops[index - 1]) {
            part = index - 1;
          }
        }
      });
      // archors.forEach((item, index) => {
      //   item.className = "";
      // });
      $("nav li a").each(function(i,v){
        v.className = "";
      });
      // archors[part].className = "active";
      $("nav li a")[part].className = "active";
    }

    window.addEventListener("scroll", () => {
      raf = requestAnimationFrame(onscroll);
    });
  },

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/80058.html

相关文章

  • mip-semi-fixed 走走又停停

    摘要:代码设计融合了业界两种实现方案,非下页面中通过更换实现,下的页面由于要特殊处理元素,所以会科隆一个节点,具体代码参考开源代码。子节点必选项需要滑动后悬浮的代码的容器,组件科隆的也是这个节点。 写在前面 MIP 中悬浮元素的特殊情况 其实组件上线已经有一段时间了,最开始看到这个需求是站长提交了一个这中功能的组件过来,不过看过代码立刻就想到了 MIP 页面的特殊性:从结果页打开的 MIP ...

    yiliang 评论0 收藏0
  • 博客改造升级

    摘要:开始之前写的个人博客确实有点太丑了,最近重写了一番。一图胜千言,且看如下效果个人博客地址项目地址自定义滚动条目前对于自定义滚动条支持情况比较好的也就只有了,所以针对有必要把滚动条的样式改造一下。典型的多对多关系。 开始 之前写的个人博客确实有点太丑了,最近重写了一番。做了移动端适配,增加了文章标签以及做了相册等功能。看着很不错。talk is cheap,show me you cod...

    Pines_Cheng 评论0 收藏0

发表评论

0条评论

Rocko

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<