vue监听页面滚动 实现吸顶效果

要求:有一个导航栏,需要实现锚点定位及滚动置顶效果

    <div class="tab-wrap" ref="navBar" :class="{ isFixed: navBarFixed }">
      <div
        class="tab-list"
        v-for="(item, index) in tabLsit"
        :key="index"
        :class="istabActive == index ? 'tab-active' : ''"
        @click="tabChlik(index)"
      >
        {{ item.tabName }}
      </div>
    </div>
  .tab-wrap {
    display: flex;
    justify-content: space-between;
    padding: 2vh 3vh;
    background: #fff;
    z-index: 2;
    &.isFixed {//实现吸顶效果
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      transition: all 0.5s ease-out, opacity 0.5s ease-out;
    }
    .tab-list {
      width: 7vh;
      line-height: 2;
      font-size: 14px;
      font-weight: 400;
      color: #000;
      font-family: "PingFangSC-Regular";
    }
    .tab-active {
      width: 7vh;
      line-height: 2;
      font-size: 15px;
      font-weight: 400;
      color: #fff;
      font-weight: bold;
      background: linear-gradient(90deg, #72bf5f, #048400);
      border-radius: 15px;
      font-family: "PingFangSC-Regular";
    }
  }
data(){
	return {
	      tabLsit: [
        {
          tabName: "a",
        },
        {
          tabName: "b",
        },
        {
          tabName: "c",
        },
        {
          tabName: "d",
        },
      ],
	}
}

#锚点定位

需要被定位的dom元素

<div id="show1"></div>
<div id="show2"></div>
<div id="show3"></div>
<div id="show4"></div>
    tabChlik(index) {
      this.istabActive = index;
      document.getElementById("show" + index).scrollIntoView();
    },

滚动置顶

在这里插入代码片
    mounted() {
      this.watchScroll();
    },
    methods: {
    watchScroll() {
      this.$nextTick(() => {
        const dom = this.$refs.navBar;
        let offsetTop = dom.offsetTop;
        window.addEventListener(
          "scroll",
          (e) => {
            let scrollTop =
              e.target.scrollTop ||
              window.pageYOffset ||
              document.documentElement.scrollTop ||
              document.body.scrollTop;
            if (this.timer) {
              clearTimeout(this.timer);
            }
            this.timer = setTimeout(() => {
              //滚动距离为包裹层距离内容层的高度
              if (scrollTop >= offsetTop) {
                this.navBarFixed = true;
              } else {
                this.navBarFixed = false;
              }
            }, 10);
          },
          true
        );
      });
    },
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值