一、实现思路
1.获取每个区域的dom,即进行滚动时每个需要滚动到顶部的
就像这样
<template>
<div class="page1" ref="page1"></div>
<div class="page2" ref="page2"></div>
<div class="page3" ref="page3"></div>
</template>
<script lang="ts" setup>
const page1 = ref<HTMLElement | null>(null);
const page2 = ref<HTMLElement | null>(null);
const page3 = ref<HTMLElement | null>(null);
<script>
2.获取它们到页面顶部的距离,然后监听鼠标滚轮滚动,根据页面距离顶部的距离进行滚动就好了
二、JS代码
// 定义页面引用
const page1Ref = ref<HTMLElement | null>(null);
const page2Ref = ref<HTMLElement | null>(null);
const page3Ref = ref<HTMLElement | null>(null);
// 页面列表及偏移量映射
const pageList = ref(new Map<HTMLElement | null, string>());
const pageOffsetTop = ref(new Map<HTMLElement | null, number>());
// 当前页面索引
const curIndex = ref(0);
onMounted(() => {
// 初始化页面列表
pageList.value.set(page1Ref.value, "首页");
pageList.value.set(page2Ref.value, "第一页");
pageList.value.set(page3Ref.value, "第二页");
// 初始化偏移量
getPageOffsetTop(pageList.value);
});
// 获取每个页面的offsetTop
const getPageOffsetTop = (pageList: Map<HTMLElement | null, string>) => {
pageList.forEach((_, key) => {
if (key) {
pageOffsetTop.value.set(key, key.offsetTop);
}
});
};
// 确定下一个页面的名称
const getNextPageName = () => {
return curIndex.value < pageList.value.size - 1
? pageList.value.get([...pageList.value.keys()][curIndex.value + 1])
: null;
};
// 确定上一个页面的名称
const getPreviousPageName = () => {
return curIndex.value > 0
? pageList.value.get([...pageList.value.keys()][curIndex.value - 1])
: null;
};
// 平滑滚动到指定页面
const smoothScrollToPage = (pageNumber: string) => {
const targetElement = Array.from(pageList.value.entries()).find(
(entry) => entry[1] === pageNumber
)?.[0];
if (targetElement && pageOffsetTop.value.has(targetElement)) {
const targetPosition = pageOffsetTop.value.get(targetElement)!;
window.scrollTo({ top: targetPosition, left: 0, behavior: "smooth" });
// 更新当前索引
curIndex.value = Array.from(pageList.value.values()).indexOf(pageNumber);
} else {
console.warn(`无法找到名为“${pageNumber}”的页面`);
}
};
// 处理滚轮滚动事件
const handleWheelScroll = (event: WheelEvent) => {
event.preventDefault();
const isScrollingDown = event.deltaY > 0;
let nextPageName = isScrollingDown
? getNextPageName()
: getPreviousPageName();
if (nextPageName) {
smoothScrollToPage(nextPageName);
}
};
// 添加滚轮监听事件
onMounted(() => {
document.addEventListener("wheel", handleWheelScroll, { passive: false });
});
// 卸载时移除监听器
onUnmounted(() => {
document.removeEventListener("wheel", handleWheelScroll);
});