有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
我使用这个解决方案,它在所有设备上都很好:
if (typeof window.orientation !== "undefined" || navigator.userAgent.indexOf('IEMobile') !== -1) {
//is_mobile
}
其他回答
如果发现仅检查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...
}
这是我在项目中使用的代码:
function isMobile() {
try {
if(/Android|webOS|iPhone|iPad|iPod|pocket|psp|kindle|avantgo|blazer|midori|Tablet|Palm|maemo|plucker|phone|BlackBerry|symbian|IEMobile|mobile|ZuneWP7|Windows Phone|Opera Mini/i.test(navigator.userAgent)) {
return true;
};
return false;
} catch(e){ console.log("Error in isMobile"); return false; }
}
var device = {
detect: function(key) {
if(this['_'+key] === undefined) {
this['_'+key] = navigator.userAgent.match(new RegExp(key, 'i'));
}
return this['_'+key];
},
iDevice: function() {
return this.detect('iPhone') || this.detect('iPod');
},
android: function() {
return this.detect('Android');
},
webOS: function() {
return this.detect('webOS');
},
mobile: function() {
return this.iDevice() || this.android() || this.webOS();
}
};
我过去用过类似的东西。这与之前的响应类似,但它在技术上更具性能,因为它缓存匹配结果,尤其是在动画、滚动事件等中使用检测时。
你不能依赖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");
}
你需要控制大小
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();