页面滚动锚点也滚动-封装了一个ts方法(定位锚点跟随页面滚动下滑)

① import { useScrollHighlight } from '@/utils/useAnchorScroll';

    // 切换滚动到对应位置锚点
    useScrollHighlight(nav_list, activeName, '.system-warp-box', 99, isClickScrolling,1,'sections-');


如果dom没渲染完的情况使用下面
  // 切换滚动到对应位置锚点
  const { handleScroll } =useScrollHighlight(nav_list, current_id, '.history-warp', 99, isClickScrolling,activeType);

  onMounted(() => {
    const el = document.querySelector('.history-warp');
    if (el) {
    el.addEventListener('scroll', handleScroll);
    }
    
  });

③// useScrollHighlight.ts方法

// useScrollHighlight.ts
import { onMounted, onBeforeUnmount,onUpdated } from 'vue';

export function useScrollHighlight(
  navListRef: any,//锚点数组
  activeNameRef: any,//active的值
  scrollContainerSelector: string,//详情容器的id
  offset = 99,
  isClickScrollingRef: any = { value: false } ,
  activeType: number = 1,//控制动态active的值
  sectionPrefix: string = 'section-', // 默认前缀,详情每个锚点详情的id
) {
  const handleScroll = () => {
    // console.log('🚀 ~ navListRef①:', navListRef?.value);
    // console.log('🚀 ~ activeNameRef②:', activeNameRef?.value);
    // console.log('🚀 ~ scrollContainerSelector③:', scrollContainerSelector);
    // console.log('🚀 ~ offset④:', offset);
    // console.log('🚀 ~ isClickScrollingRef⑤:', isClickScrollingRef?.value);

    if (isClickScrollingRef?.value) return;

    const scrollContainer = document.querySelector(scrollContainerSelector);
    if (!scrollContainer) return;
    const containerRect = scrollContainer.getBoundingClientRect();

    for (let i = navListRef.value.length - 1; i >= 0; i--) {
      const sectionType = `${sectionPrefix}${navListRef.value[i].id}`;
      const section = document.getElementById(sectionType);
      if (section) {
        const rect = section.getBoundingClientRect();
        const relativeTop = rect.top - containerRect.top;

        if (relativeTop <= offset) {
          activeNameRef.value =
            activeType === 1
              ? 'tab' + navListRef.value[i].id
              : navListRef.value[i].id;
          break;
        }
      }
    }
  };

  onUpdated(() => {
    const scrollContainer =  document.querySelector(scrollContainerSelector);
    scrollContainer?.addEventListener('scroll', handleScroll);
  });

  onBeforeUnmount(() => {
    const scrollContainer = document.querySelector(scrollContainerSelector);
    scrollContainer?.removeEventListener('scroll', handleScroll);
  });

  return { handleScroll };
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值