锚点

<template>
  <div ref="height" class="wrap">
    <div class="tab">
      <div @click="get(v)" :class="{ 'active': v === num }" v-for="(i, v) in listtab" :key="v">{{ i.name }}</div>
    </div>
    <div class="conten">
      <div class="conten1 right0">{{ heights }}</div>
      <div ref="conten2" class="conten2 right1">{{ heights }}</div>
      <div class="conten3 right2">{{ heights }}</div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, ref, toRefs } from 'vue'

export default defineComponent({
  setup() {
    const tab = reactive({
      listtab: [
        {
          name: '关注1'
        },
        {
          name: '关注2'
        },
        {
          name: '关注3'
        }
      ]
    })
    const trues = ref(false)
    const num = ref(0)
    const height = ref()
    const heights = ref()
    const conten2 = ref()
    function get(key: number) {
      num.value = key
      var PageId: any = document.querySelector(".right" + key);
      window.scrollTo({
        top: PageId.offsetTop,
        behavior: 'smooth'
      })
    }
    function scroll() {
      // 获取滚动值
      var scroll_top = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0
      // 控制台查看滚动值
      conten2.value.pageYOffset
      console.log(scroll_top);
      // heights.value = height.value.clientHeight
      var PageId: any = document.querySelector(".right" + 0);
      var PageId1: any = document.querySelector(".right" + 1);
      var PageId2: any = document.querySelector(".right" + 2);
      console.log('30', PageId.getBoundingClientRect().top);
      document.getElementById('asd')?.scrollTop
      if (PageId.getBoundingClientRect().top < height.value.clientHeight) {
        num.value = 0
      }
      if (PageId1.getBoundingClientRect().top < height.value.clientHeight) {
        num.value = 1
      }
      if (PageId2.getBoundingClientRect().top < height.value.clientHeight) {
        num.value = 2
      }


    }
    onMounted(() => {
      window.addEventListener("scroll", scroll);
    })
    return { scroll, trues, conten2, heights, height, num, get, ...toRefs(tab) }
  }
})
</script>


<style lang="less" scoped>
.active {
  color: gold;
}


.wrap {
  position: relative;
  width: 500px;
  height: calc(100vh);
}

.anction {
  color: red;
}

.tab {
  border: 1px solid red;
  position: fixed;
  // display: flex;
  width: 100%;
  // z-index: 100;
}

.conten {
  width: 100%;
  border: 1px solid red;
}

.conten1,
.conten2,
.conten3 {
  width: 100%;
  height: 800px;
}

.conten1 {
  background: green;
}

.conten2 {
  background: orange;
}

.conten3 {
  background: red;
}
</style>

  

posted @ 2022-08-23 19:04  zjxgdq  阅读(12)  评论(0编辑  收藏  举报