有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
你需要控制大小
var is_mobile = false;
$(window).resize(function() {
if ($('#mobileNav').css('display') == 'block') {
is_mobile = true;
}
if (is_mobile == true) {
console.log('is_mobile')
document.addEventListener(
"DOMContentLoaded", () => {
new Mmenu("#mainMenu", {
"offCanvas": {
"position": "right-front"
}
});
}
);
}
}).resize();
其他回答
我建议使用以下字符串组合,以检查是否使用了设备类型。
根据Mozilla文档字符串,建议使用Mobi。但是,如果只使用Mobi,一些旧的平板电脑不会返回真值,因此我们也应该使用Tablet字符串。
同样,为了安全起见,iPad和iPhone字符串也可以用来检查设备类型。
大多数新设备将仅对Mobi字符串返回true。
if (/Mobi|Tablet|iPad|iPhone/.test(navigator.userAgent)) {
// do something
}
在一行javascript中:
var isMobile = ('ontouchstart' in document.documentElement && /mobi/i.test(navigator.userAgent));
如果用户代理包含“Mobi”(根据MDN)并且ontouchstart可用,那么它很可能是一个移动设备。
EDIT:根据评论中的反馈更新正则表达式代码。使用regex/mobi/i,i不区分大小写,mobi匹配所有移动浏览器。看见https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox
这里还有一个使用纯JavaScript实现的建议(es6)
const detectDeviceType = () =>
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
? 'Mobile'
: 'Desktop';
detectDeviceType();
根据您想要检测移动设备的原因(这意味着这个建议不适合每个人的需要),您可以通过查看onmouseenter来实现区分,以单击毫秒差异,就像我在这个答案中描述的那样。
在以下位置找到解决方案:http://www.abeautifulsite.net/blog/2011/11/detecting-mobile-devices-with-javascript/.
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
然后,要验证它是否是移动设备,您可以使用以下方法进行测试:
if(isMobile.any()) {
//some code...
}