如何在Wear OS Compose中用单个函数检测全屏滑动手势?
全屏滑动手势检测的简洁实现
单个函数实现代码
function detectSwipe(onSwipe) { let startX, startY; const threshold = 50; // 滑动触发阈值,单位px // 记录滑动起始位置 const handleStart = (e) => { const event = e.touches ? e.touches[0] : e; startX = event.clientX; startY = event.clientY; }; // 判断滑动方向并触发回调 const handleEnd = (e) => { if (!startX || !startY) return; const event = e.changedTouches ? e.changedTouches[0] : e; const endX = event.clientX; const endY = event.clientY; const diffX = endX - startX; const diffY = endY - startY; // 过滤误触,仅处理超过阈值的有效滑动 if (Math.abs(diffX) > threshold || Math.abs(diffY) > threshold) { const direction = Math.abs(diffX) > Math.abs(diffY) ? (diffX > 0 ? 'right' : 'left') : (diffY > 0 ? 'down' : 'up'); onSwipe?.(direction); } // 重置起始坐标 startX = startY = null; }; // 绑定全屏事件监听 document.addEventListener('touchstart', handleStart, { passive: true }); document.addEventListener('touchend', handleEnd, { passive: true }); document.addEventListener('mousedown', handleStart); document.addEventListener('mouseup', handleEnd); // 返回清理函数,用于移除监听释放资源 return () => { document.removeEventListener('touchstart', handleStart); document.removeEventListener('touchend', handleEnd); document.removeEventListener('mousedown', handleStart); document.removeEventListener('mouseup', handleEnd); }; } // 使用示例 const removeSwipeListener = detectSwipe((direction) => { console.log(`检测到滑动:${direction}`); }); // 停止监听时调用:removeSwipeListener();
实现步骤解释
- 闭包维护状态:用函数内部变量
startX/startY保存滑动起点,既避免全局变量污染,又保证事件回调能访问到状态。 - 兼容多端场景:同时绑定触摸(移动端)和鼠标(桌面端)事件,覆盖不同设备的滑动操作;
passive: true优化移动端触摸事件的响应性能。 - 记录起始坐标:在
touchstart/mousedown触发时,获取触点相对于视口的坐标,作为滑动的起始基准。 - 计算滑动偏移:在
touchend/mouseup时,计算终点与起点的坐标差,通过阈值过滤掉误触的微小滑动。 - 判断滑动方向:比较X轴和Y轴的偏移量绝对值,优先判断水平/垂直方向,最终输出明确的滑动方向。
- 提供清理机制:返回移除事件监听的函数,方便在不需要检测时释放资源,避免内存泄漏。
内容的提问来源于stack exchange,提问作者Kerbal Space Program Germany
相关产品推荐
相关产品推荐

