vue中实现锚点定位以及平滑滚动到指定位置

在这里插入图片描述
代码:

<template>
  <div class="process-details-container">
    <div class="left-box">
      <div
        v-for="(item, index) in titelList"
        :key="item.id"
        :class="activeIndex == index ? 'btn btn-active' : 'btn'"
        @click="navClick(item, index)"
      >{{ item.title }}</div>
    </div>
    <div class="right-box" @scroll="onScroll">
      <div v-for="item in titelList" :key="item.id" :id="item.id" class="section-box">
        <div class="title">{{ item.title }}</div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      titelList: [
        {
          title: '党委会阶段',
          id: 'conferenceStage',
          top: '',
        },
        {
          title: '招标阶段',
          id: 'biddingPhase',
          top: '',
        },
        {
          title: '合同执行情况',
          id: 'contractExecution',
          top: '',
        },
        {
          title: '结题资料',
          id: 'concludingData',
          top: '',
        }
      ],
      activeIndex: 0,

    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.titelList.forEach(item => {
        let anchor = document.getElementById(item.id);
        item.top = anchor.offsetTop;
      })
      // console.log(this.titelList);
    },
    navClick(item, index) {
      this.activeIndex = index;

      let anchor = document.getElementById(item.id);
      // console.log(anchor.offsetTop, 'top');
      anchor.scrollIntoView({ behavior: "smooth" });
    },
    onScroll(e) {
      // console.log(e.target.scrollTop, 'scroll');
      this.titelList.map((item, index) => {
        if (e.target.scrollTop >= item.top) {
          this.activeIndex = index;
        }
      })
    },

  }
}
</script>

<style lang="scss" scoped>
.process-details-container {
  position: relative;
  width: 100%;
  height: 700px;
  display: flex;
  align-items: center;

  .left-box {
    width: 200px;
    height: 100%;
    background-color: #eef1f6;

    .btn {
      padding: 0 20px;
      height: 50px;
      line-height: 50px;
      cursor: pointer;
    }

    .btn:hover {
      color: #1890ff;
      background-color: #c8d6f0;
    }

    .btn-active {
      color: #1890ff;
      background-color: #c8d6f0;
    }
  }

  .right-box {
    width: calc(100% - 200px);
    height: 100%;
    padding: 0 20px;
    overflow: auto;

    .section-box {
      width: 100%;
      height: 500px;

      .title {
        width: 100%;
        height: 40px;
        line-height: 40px;
        padding: 0 10px;
        background-color: #7db6eb;
        color: #fff;
      }
    }
  }
}
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值