每当用户输入类型改变( mouse
或 touch
)时运行回调。用于根据输入设备启用/禁用代码。这个过程是动态的,适用于混合设备(例如触摸屏笔记本电脑)。
使用两个事件监听器。首先假设 mouse
输入并将 touchstart
事件监听器绑定到 document
上。在 touchstart
上,添加一个 mousemove
事件监听器来侦听连续两个 mousemove
事件在 20ms 内触发,使用 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.'); });
更多代码 JavaScript 实用代码片段 请查看 https://www.html.cn/30-seconds-of-code/
最新评论
写的挺好的
有没有兴趣翻译 impatient js? https://exploringjs.com/impatient-js/index.html
Flexbox playground is so great!
感谢总结。
awesome!
这个好像很早就看到类似的文章了
比其他的教程好太多了
柯理化讲的好模糊…没懂