有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
一种简单有效的内衬:
function isMobile() { return ('ontouchstart' in document.documentElement); }
然而,上述代码没有考虑到带有触摸屏的笔记本电脑的情况。因此,我提供了基于@Julian解决方案的第二个版本:
function isMobile() {
try{ document.createEvent("TouchEvent"); return true; }
catch(e){ return false; }
}
其他回答
function isDeviceMobile(){
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i) && navigator.userAgent.match(/mobile|Mobile/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i)|| navigator.userAgent.match(/BB10; Touch/);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i) || navigator.userAgent.match(/webOS/i) ;
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
return isMobile.any()
}
所有答案都使用用户代理来检测浏览器,但基于用户代理的设备检测不是很好的解决方案,最好是检测触摸设备等功能(在新的jQuery中,他们删除了$.browser,改用$.support)。
要检测移动设备,您可以检查触摸事件:
function is_touch_device() {
return 'ontouchstart' in window // works on most browsers
|| 'onmsgesturechange' in window; // works on ie10
}
摘自使用JavaScript检测“触摸屏”设备的最佳方法是什么?
你需要控制大小
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();
在一行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
我知道这是一个关于这种检测的老问题。
我的解决方案基于滚动条宽度(是否存在)。
//此函数将检查滚动条的宽度//如果滚动条宽度为0px,则为移动设备//函数ismob(){var dv=文档.getElementById('divscr');var sp=文档.getElementById('res');如果(dv.offsetWidth-dv.clientWidth==10){sp.innerHTML=“是移动的”;//返回true;}其他{sp.innerHTML=“它不是移动的”//return false;}//}<!-- 将隐藏的div放在页面-->的开头</div><span id=“res”></span>