uniapp 滑动事件监听在pc端浏览器不生效怎么办?

在uniapp开发中,我使用@touchmove@scroll监听滑动事件,在移动端正常,但在PC端浏览器完全没反应。测试发现Chrome和Edge都不触发事件,改用@mousemove虽然能响应但不符合滑动场景需求。请问如何让滑动事件在PC浏览器正常生效?是否需要特殊处理或兼容写法?

2 回复

在PC端,给元素添加@touch事件可能无效,建议同时绑定@mouse事件,如@mousedown@mousemove@mouseup。或者使用第三方库如@vueuse/gesture统一处理触摸和鼠标事件。


在UniApp中,滑动事件(如 touchstarttouchmovetouchend)在PC端浏览器可能不生效,因为PC端通常使用鼠标事件。解决方法如下:

1. 使用 @touch@mouse 事件组合

在模板中同时绑定触摸事件和鼠标事件,确保PC和移动端兼容。

<template>
  <view 
    @touchstart="handleStart"
    @touchmove="handleMove"
    @touchend="handleEnd"
    @mousedown="handleStart"
    @mousemove="handleMove"
    @mouseup="handleEnd"
  >
    滑动区域
  </view>
</template>

<script>
export default {
  methods: {
    handleStart(e) {
      // 处理滑动开始,e 可能是触摸事件或鼠标事件
      console.log('滑动开始', e);
    },
    handleMove(e) {
      // 处理滑动中
      console.log('滑动中', e);
    },
    handleEnd(e) {
      // 处理滑动结束
      console.log('滑动结束', e);
    }
  }
}
</script>

2. 统一事件数据处理

由于触摸事件和鼠标事件结构不同,需提取公共坐标信息:

getEventPosition(e) {
  if (e.touches && e.touches.length > 0) {
    return { x: e.touches[0].clientX, y: e.touches[0].clientY };
  } else if (e.clientX) {
    return { x: e.clientX, y: e.clientY };
  }
  return { x: 0, y: 0 };
}

handleStarthandleMove 中调用此方法获取坐标。

3. 使用第三方库

考虑使用 hammerjsalloyfinger 等库处理跨端手势,但需手动引入。

4. 检查浏览器兼容性

确保PC浏览器支持事件监听,可在 mounted 中测试:

mounted() {
  if (typeof window !== 'undefined') {
    console.log('环境支持鼠标事件');
  }
}

注意事项:

  • 在PC端测试时,开启浏览器开发者工具的移动端模拟可能仍不触发鼠标事件,直接使用PC模式测试。
  • 若使用区域滚动组件(如 scroll-view),需确认事件是否被阻止。

通过以上方法,可解决UniApp滑动事件在PC端不生效的问题。

回到顶部