<template>
<div class="page-container" ref="scrollRef" @touchstart="handleTouchStart" @touchend="handleTouchEnd">
<!-- 页面内容 -->
<template v-for="i in list" :key="i">
<div class="" style="width:100%;height:100vh;">
{{ i }}
</div>
</template>
</div>
</template>
<script setup>
import { onMounted, ref } from 'vue';
const startY = ref(0)// 触摸开始的Y坐标
const endY = ref(0)//触摸结束的Y坐标
const threshold = ref(10)//判断为滑动的最小距离
const list = ref([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])//判断为滑动的最小距离
const currentIndex = ref(0)//触摸结束的Y坐标
const scrollRef = ref(null) //ref
const viewportHeightInPx = ref(0)//100vh的高度
onMounted(() => {
viewportHeightInPx.value = window.innerHeight;
})
function handleTouchStart(e) {
startY.value = e.touches[0].clientY;
console.log('开始触摸', startY.value)
}
function handleTouchEnd(e) {
endY.value = e.changedTouches[0].clientY;
if (endY.value - startY.value > threshold.value) {
// 向下滑动
goToNextPage();
} else if (startY.value - endY.value > threshold.value) {
// 向上滑动
goToPrevPage();
}
}
function goToNextPage() {
// 实现翻到下一页的逻辑
console.log('下滑,翻到下一页');
currentIndex.value -= 1;
init()
}
function goToPrevPage() {
// 实现翻到上一页的逻辑
console.log('上滑,翻到上一页');
currentIndex.value += 1;
init()
}
const init = () => {
if (currentIndex.value < 0) {
currentIndex.value = 0
}
if (scrollRef.value) {
scrollRef.value.scrollTo({
top: (viewportHeightInPx.value * currentIndex.value),
behavior: 'smooth', // 为了平滑滚动效果
});
}
}
</script>
<style>
.page-container {
height: 100vh;
/* 确保页面高度占满全屏 */
overflow-y: auto;
/* 允许滚动 */
}
.content {
background: url('@/assets/1/bg.png');
background-size: cover;
}
</style>
h5滑动翻页(滚动到下一个元素)vue3.2
最新推荐文章于 2024-06-25 10:05:02 发布