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

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://segmentfault.com/a/1190000006233176
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞