Demo记录|移动端H5页面如何实现上下滑动触发事件的小功能

16541198:

Demo记录|移动端H5页面如何实现上下滑动触发事件的小功能

简单记录一个小demo,如果写h5页面比较实用,可以实现一些有趣的功能。
我这里主要是用来另类的实现抖音视频上下切换播放,因为视频涉及的选集,不能按照网上大部分的使用列表切换来实现上下切换播放,所以使用上下滑动到一个临界点来触发切换播放事件。

实现效果

页面是在手机端via游览器上进行的实测。
页面如下:
请添加图片描述
当进行向下滑动时:
如果滑动的距离超过了100,则在停止滑动时触发对应的alert事件,且通过transform属性进行了页面y轴的实时位移。
请添加图片描述
同样的原理,当进行向上滑动时:
请添加图片描述

代码实现

代码是使用vue3实现,注释很清楚,可以根据原理进行代码转换。

<script setup>
import {
    
     onMounted, onUnmounted, ref } from 'vue';

// 在组件挂载时绑定触摸事件
onMounted(() => {
    
    
  window.addEventListener('touchstart', handleTouchStart);
  window.addEventListener('touchmove', handleTouchMove);
  window.addEventListener('touchend', handleTouchEnd);
});

// 在组件卸载时解绑触摸事件
onUnmounted(() => {
    
    
  window.removeEventListener('touchstart', handleTouchStart);
  window.removeEventListener('touchmove', handleTouchMove);
  window.removeEventListener('touchend', handleTouchEnd);
});

const startY = ref(0); // 记录触摸开始的Y坐标
const moveY = ref(0); // 记录滑动的Y距离
const isMoving = ref(false); // 是否正在滑动

// 监听touchstart事件,记录触摸开始的Y坐标
const handleTouchStart = (e) => {
    
    
  startY.value = e.touches[0].clientY;
};
// 监听touchmove事件,计算滑动的Y距离
const handleTouchMove = (e) => {
    
    
  if(!isMoving.value) {
    
    
    isMoving.value = true;
  }
  moveY.value = e.touches[0].clientY - startY.value;
};
// 监听touchend事件,判断滑动的距离是否超过100px,并执行相应的事件
const handleTouchEnd = () => {
    
    
  if(isMoving.value && moveY.value >= 100) {
    
    
    alert('向下滑动超过100px了');
  }
  if(isMoving.value && moveY.value <= -100) {
    
    
    alert('向上滑动超过100px了');
  }
  startY.value = 0;
  moveY.value = 0;
  isMoving.value = false;
};

</script>

<template>
  <!-- 通过transform实现滑动时页面的跟随 -->
  <div class="root" :style="{ transform: `translateY(${moveY}px)` }">
    <h3>Demo Page</h3>
    <p>滑动距离:{
    
    {
    
    moveY}}</p>
  </div>
</template>

<style lang="less" scoped>
.root {
    
    
  width: 100%;
  height: 100%;

  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  position: relative;
  background-color: rgb(0, 255, 234);
}
</style>

猜你喜欢

转载自blog.csdn.net/qq_44886882/article/details/132719087