我正在开发一个webapp(不是一个有趣文本页面的网站),它有一个非常不同的触摸界面(当你点击时你的手指隐藏屏幕)和鼠标(严重依赖于悬停预览).如何检测到我的用户没有鼠标向他显示正确的界面?我计划为鼠标和触摸的人留下一个开关(就像一些笔记本电脑).
浏览器中的触摸事件功能实际上并不意味着用户正在使用触摸设备(例如,Modernizr不会剪切它).如果设备有鼠标,正确回答问题的代码应该返回false,否则返回true.对于具有鼠标和触摸功能的设备,它应该返回false(不是仅触摸)
作为旁注,我的触摸界面可能也适用于仅限键盘的设备,因此更多的是缺少我想要检测的鼠标.
为了使需求更加清晰,以下是我要实现的API:
// Level 1
// The current answers provide a way to do that.
hasTouch();
// Returns true if a mouse is expected.
// Note: as explained by the OP, this is not !hasTouch()
// I don't think we have this in the answers already, that why I offer a bounty
hasMouse();
// Level 2 (I don't think it's possible, but maybe I'm wrong, so why not asking)
// callback is called when the result of "hasTouch()" …Run Code Online (Sandbox Code Playgroud) 为了遵循最佳实践,我们尝试根据您使用的设备使用正确的JavaScript/jQuery事件.例如,我们正在构建一个移动网站,其中包含一个带有onclick或touch事件的标记.对于iPhone,我们想使用"touchstart"活动.在将该处理程序绑定到对象之前,我们想测试他们的设备是否支持"touchstart".如果没有,那么我们将绑定"onclick".
做这个的最好方式是什么?
我知道很多JavaScript库依赖于"ontouchstart"来检测它是在平板电脑还是桌面上.
这是我正在谈论的代码示例:
var hasTouch = ("ontouchstart" in window);
Run Code Online (Sandbox Code Playgroud)
目前,我不得不注释掉所有平板电脑检测代码才能正常工作.
检测平板电脑与台式机的最佳方法是什么?
谢谢!