diff --git a/src/App.vue b/src/App.vue index 404c37215b94e6a6096fb1418cfd970937c44353..92dc1768dd33b9dbd9b8430e2cfb75a7ca1c29b2 100644 --- a/src/App.vue +++ b/src/App.vue @@ -51,6 +51,18 @@ },0) } + const scrollTimer = ref(null); // 定时器引用 + const currentScreenIndex = ref(0); // 当前屏索引 + const isInteracting = ref(false); + + + // 判断第几屏吗 + const changeSwiperIndex = (index:number) =>{ + currentScreenIndex.value=index + console.log('当前第'+(currentScreenIndex.value+1)+'屏') + } + + const handleScroll = () => { if (!scrollContainer.value) return; @@ -60,8 +72,25 @@ const maxScroll = container.scrollWidth - container.clientWidth - 5 - isLeftEdge.value=currentScroll < 5 - isRightEdge.value=currentScroll >= maxScroll + nextTick(() => { + isLeftEdge.value = currentScroll < 5; + isRightEdge.value = currentScroll >= maxScroll; + // console.log(isLeftEdge.value, isRightEdge.value) + }); + + // 清除之前的定时器 + if (scrollTimer.value) { + clearTimeout(scrollTimer.value); + scrollTimer.value = null; + } + if (!isInteracting.value) { + scrollTimer.value = setTimeout(() => { + // 计算当前滚动到第几屏 + const screenWidth = container.clientWidth; + const currentScreen = Math.round(currentScroll / screenWidth); + changeSwiperIndex(currentScreen) + }, 100); // + } }; onMounted(() => { @@ -70,11 +99,34 @@ container.scrollLeft = container.scrollLeft + 1; } if (scrollContainer.value) { - scrollContainer.value.addEventListener('scroll', handleScroll); + scrollContainer.value.addEventListener('touchstart', () => { + isInteracting.value = true; // 标记用户开始交互 + }); + + scrollContainer.value.addEventListener('touchend', () => { + isInteracting.value = false; // 标记用户结束交互 + handleScroll(); // 立即触发滚动计算 + }); + + // 添加鼠标事件监听(兼容桌面端) + scrollContainer.value.addEventListener('mousedown', () => { + isInteracting.value = true; + }); + + scrollContainer.value.addEventListener('mouseup', () => { + isInteracting.value = false; + handleScroll(); + }); + scrollContainer.value.removeEventListener('scroll', handleScroll); + scrollContainer.value.addEventListener('scroll', handleScroll); } }) onBeforeUnmount(() => { if (scrollContainer.value) { + scrollContainer.value.removeEventListener('touchstart', () => {}); + scrollContainer.value.removeEventListener('touchend', () => {}); + scrollContainer.value.removeEventListener('mousedown', () => {}); + scrollContainer.value.removeEventListener('mouseup', () => {}); scrollContainer.value.removeEventListener('scroll', handleScroll); } });