有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
移动设备的具体功能是什么,这意味着你想要不同的行为?
是输入机制(触摸和虚拟键盘与鼠标和物理键盘)、更小的屏幕尺寸还是其他原因?
例如,在CSS4中,您可以为支持触摸的设备使用@media(任何指针:粗糙),而为主要输入为触摸的设备(即,无论是否插入外部键盘,手机和平板电脑)使用@media(指针:粗略)。现代浏览器大多完全支持CSS4。
在JavaScript中,您可以使用Window.matchMedia()测试任何CSS媒体查询(包括上面的查询),如本SO答案中所建议的。(我本来希望现在能有更本土的东西,但找不到任何东西。)
其他回答
很好的回答,谢谢。支持Windows phone和Zune的小改进:
if (navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/webOS/i) ||
navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPad/i) ||
navigator.userAgent.match(/iPod/i) ||
navigator.userAgent.match(/BlackBerry/) ||
navigator.userAgent.match(/Windows Phone/i) ||
navigator.userAgent.match(/ZuneWP7/i)
) {
// some code
self.location = "top.htm";
}
如果通过移动设备您了解可触摸设备,则可以通过检查触摸处理器的存在来确定:
let deviceType = (('ontouchstart' in window)
|| (navigator.maxTouchPoints > 0)
|| (navigator.msMaxTouchPoints > 0)
) ? 'touchable' : 'desktop';
它不需要jQuery。
如果发现仅检查navigator.userAgent并不总是可靠的。还可以通过检查navigator.platform来实现更高的可靠性。对先前答案的简单修改似乎效果更好:
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ||
(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform))) {
// some code...
}
仅使用matchMedia的IE10+解决方案:
const isMobile = () => window.matchMedia('(max-width: 700px)').matches
isMobile()返回布尔值
mobiledetect.net怎么样?
其他解决方案似乎过于基础。这是一个轻量级的PHP类。它使用用户代理字符串和特定的HTTP标头来检测移动环境。您还可以通过使用任何第三方插件从Mobile Detect中获益:WordPress、Drupal、Joomla、Magento等。