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
        );
      });
    },
 }

你可能感兴趣的:(vue.js,前端,javascript)