有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
我建议使用以下字符串组合,以检查是否使用了设备类型。
根据Mozilla文档字符串,建议使用Mobi。但是,如果只使用Mobi,一些旧的平板电脑不会返回真值,因此我们也应该使用Tablet字符串。
同样,为了安全起见,iPad和iPhone字符串也可以用来检查设备类型。
大多数新设备将仅对Mobi字符串返回true。
if (/Mobi|Tablet|iPad|iPhone/.test(navigator.userAgent)) {
// do something
}
其他回答
一种简单有效的内衬:
function isMobile() { return ('ontouchstart' in document.documentElement); }
然而,上述代码没有考虑到带有触摸屏的笔记本电脑的情况。因此,我提供了基于@Julian解决方案的第二个版本:
function isMobile() {
try{ document.createEvent("TouchEvent"); return true; }
catch(e){ return false; }
}
navigator.userAgentData.mobile返回[true|false]
我建议你结账http://wurfl.io/
简而言之,如果您导入一个很小的JavaScript文件:
<script type='text/javascript' src="//wurfl.io/wurfl.js"></script>
您将看到一个JSON对象,其外观如下:
{
"complete_device_name":"Google Nexus 7",
"is_mobile":true,
"form_factor":"Tablet"
}
(当然,这是假设您正在使用Nexus 7),您将能够执行以下操作:
if(WURFL.is_mobile) {
//dostuff();
}
这就是你要找的。
免责声明:我为提供这项免费服务的公司工作。
屏幕可能位于分辨率较小的桌面上,也可能位于分辨率较宽的手机上,因此,结合本问题中的两个答案
const isMobile = window.matchMedia("only screen and (max-width: 760px)");
if (/Mobi|Tablet|iPad|iPhone/i.test(navigator.userAgent) || isMobile.matches) {
console.log('is_mobile')
}
如果您使用Modernizr,那么很容易使用前面提到的Modernizr.touch。
然而,为了安全起见,我更喜欢使用Moderniz.touch和用户代理测试的组合。
var deviceAgent = navigator.userAgent.toLowerCase();
var isTouchDevice = Modernizr.touch ||
(deviceAgent.match(/(iphone|ipod|ipad)/) ||
deviceAgent.match(/(android)/) ||
deviceAgent.match(/(iemobile)/) ||
deviceAgent.match(/iphone/i) ||
deviceAgent.match(/ipad/i) ||
deviceAgent.match(/ipod/i) ||
deviceAgent.match(/blackberry/i) ||
deviceAgent.match(/bada/i));
if (isTouchDevice) {
//Do something touchy
} else {
//Can't touch this
}
如果您不使用Modernizr,您可以简单地将上面的Modernizr.touch函数替换为(document.documentElement中的“ntouchstart”)
还要注意,测试用户代理iemobile将为您提供比Windows Phone更广泛的检测到的Microsoft移动设备。
另请参阅此SO问题