有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
屏幕可能位于分辨率较小的桌面上,也可能位于分辨率较宽的手机上,因此,结合本问题中的两个答案
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')
}
其他回答
MDN建议使用Navigator.maxTouchPoints检查可用的可触摸点。如果>0,则设备是可触摸的,很可能是手机或平板电脑。https://developer.mozilla.org/en-US/docs/Web/API/Navigator/maxTouchPoints
使用此
if( screen.width <= 480 ) {
// is mobile
}
你不能依赖navigator.userAgent,并不是每个设备都会显示其真实的操作系统。例如,在我的HTC上,这取决于设置(“使用移动版本”开/关)。在…上http://my.clockodo.com,我们只是使用screen.width来检测小型设备。不幸的是,在某些Android版本中,screen.width存在一个错误。您可以将这种方式与userAgent结合起来:
if(screen.width < 500 ||
navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/webOS/i) ||
navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPod/i)) {
alert("This is a mobile device");
}
添加:
在某些版本的iOS 9.x中,Safari不会在navigator.userAgent中显示“iPhone”,而是在navigater.platform中显示。
var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent);
if(!isMobile){
isMobile=/iPhone|iPad|iPod/i.test(navigator.platform);
}
你也可以像下面这样检测它
$.isIPhone = function(){
return ((navigator.platform.indexOf("iPhone") != -1) || (navigator.platform.indexOf("iPod") != -1));
};
$.isIPad = function (){
return (navigator.platform.indexOf("iPad") != -1);
};
$.isAndroidMobile = function(){
var ua = navigator.userAgent.toLowerCase();
return ua.indexOf("android") > -1 && ua.indexOf("mobile");
};
$.isAndroidTablet = function(){
var ua = navigator.userAgent.toLowerCase();
return ua.indexOf("android") > -1 && !(ua.indexOf("mobile"));
};