当前位置:   article > 正文

vue3组件 描点定位以及监听滚动切换对应activeTab_vue3的html的锚点监听

vue3的html的锚点监听

描点定位以及监听滚动切换对应activeTab

基本逻辑

  1. init 初始化 获取滚动区域内所有非文本子节点
  2. offsetTopArr 存储所有子节点的高度
  3. scroll 监听滚动的距离,找到还在可视区的元素高度
<template>
  <div class="tab-list">
    <div v-for="item in menuList" class="item" :class="{ 'is-active': active === item.value }">
      <a :href="`#${item.value}`" @click="active = item.value">{{ item.label }}</a>
    </div>
  </div>
  <div class="scroll-content" @scroll="handleScroll">
    <slot />
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue';
import { throttle } from 'lodash';

interface propsType {
  menuList: Array<{
    label: string;
    value: string;
  }>;
  parentClass: string;
}
const props = withDefaults(defineProps<propsType>(), {
  menuList: () => [],
});

const active = ref(props.menuList[0].value);

const offsetTopArr = ref([]);
const curIndex = ref(0);

const init = () => {
  const parentNode = document.querySelector(props.parentClass);
  const childNodesAll = parentNode.childNodes;
  for (let index = 0; index < childNodesAll.length; index++) {
    const child = childNodesAll[index];
    if (child.nodeType === 1) offsetTopArr.value.push(child.offsetTop);
  }
};

const handleScroll = throttle((e) => {
  curIndex.value = offsetTopArr.value.findIndex((item) => {
    return e.target.scrollTop <= item;
  });
  active.value = props.menuList[curIndex.value].value;
}, 200);

onMounted(() => {
  nextTick(init);
});
</script>

<style lang="scss" scoped>
.tab-list {
  height: 100%;
  width: 120px;
}
.scroll-content {
  width: 100%;
  height: 100%;
  overflow-y: auto;
}
</style>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/529180
推荐阅读
相关标签
  

闽ICP备14008679号