页面滚动锚点也滚动-封装了一个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,//详情容器的idoffset = 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 };
}