如何使用 JS/jQuery 检查浏览器是否支持 touchstart?
为了遵循最佳实践,我们尝试根据您使用的设备使用正确的 JavaScript/jQuery 事件。例如,我们正在构建一个移动网站,该网站的标签将具有 onclick 或 touch 事件。对于 iPhone,我们想使用“touchstart”事件。在将该处理程序绑定到对象之前,我们想测试他们的设备是否支持“touchstart”。如果没有,那么我们将绑定“onclick”。
最好的方法是什么?
In an attempt to follow best practices, we're trying to use the proper JavaScript/jQuery events according to what device you are using. For example, we're building a mobile site that has an tag that will have an onclick or touch event. In the case of an iPhone, we'd like to use the "touchstart" event. We'd like to test if their device supports "touchstart" before we bind that handler to the object. If it doesn't, then we will bind "onclick" instead.
What is the best way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以通过以下方式检测事件是否受支持:
查看本文:
那里发布的
isEventSupported
函数非常擅长检测各种事件,而且是跨浏览器的。You can detect if the event is supported by:
Give a look to this article:
The
isEventSupported
function published there, is really good at detecting a wide variety of events, and it's cross-browser.使用此代码检测设备是否支持触摸。
也适用于 Windows 8 IE10,它使用“MSPointerDown”事件而不是“touchmove”
Use this code to detect if the device supports touch.
Also work for windows 8 IE10 which uses 'MSPointerDown' event instead of 'touchmove'
您可以检查
typeof document.body.ontouchstart == "undefined"
是否回退到正常的 dom 事件You could check if
typeof document.body.ontouchstart == "undefined"
to fall back to normal dom events我做了一个完整的演示,适用于每个浏览器,并提供了该问题解决方案的完整源代码:在 Javascript 中检测触摸屏设备。
I made a full demostration that works in every browser with the full source code of the solution of this problem: Detect touch screen devices in Javascript.