2019-11-29
描述
当用户输入方式发生变化(mouse
or touch
)时运行回调。根据输入设备启用/禁用代码很有用。这个过程时动态的,并且适用于混合设备(例如:触摸屏笔记本电脑)。
提示
- 使用两个事件监听器
- 假设一开始的输入为
mouse
,然后在文档上绑定一个touchstart
事件监听 - 在
touchstart
中添加一个mousemove
事件监听器来监听两次连续的mousemove
事件触发是否在 20 ms 内(使用performance.now()
) - 在这两种情况下都将输入类型作为回调函数中的参数进行运行
代码
const onUserInputChange = callback => { let type = 'mouse', lastTime = 0; const mousemoveHandler = () => { const now = performance.now(); if (now - lastTime < 20) (type = 'mouse'), callback(type), document.removeEventListener('mousemove', mousemoveHandler); lastTime = now; }; document.addEventListener('touchstart', () => { if (type === 'touch') return; (type = 'touch'), callback(type), document.addEventListener('mousemove', mousemoveHandler); }); };
示例
输入方式改变后输出相关日志:
onUserInputChange(type => { console.log('The user is now using', type, 'as an input method.'); });
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于