有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
我尝试了一些方法,然后我决定手动填写一个列表并进行简单的JS检查。最后,用户必须确认。因为有些检查给出了假阳性或阴性。
var isMobile = false;
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Opera Mobile|Kindle|Windows Phone|PSP|AvantGo|Atomic Web Browser|Blazer|Chrome Mobile|Dolphin|Dolfin|Doris|GO Browser|Jasmine|MicroB|Mobile Firefox|Mobile Safari|Mobile Silk|Motorola Internet Browser|NetFront|NineSky|Nokia Web Browser|Obigo|Openwave Mobile Browser|Palm Pre web browser|Polaris|PS Vita browser|Puffin|QQbrowser|SEMC Browser|Skyfire|Tear|TeaShark|UC Browser|uZard Web|wOSBrowser|Yandex.Browser mobile/i.test(navigator.userAgent) && confirm('Are you on a mobile device?')) isMobile = true;
现在,如果您想使用jQuery设置CSS,可以执行以下操作:
$(document).ready(function() {
if (isMobile) $('link[type="text/css"]').attr('href', '/mobile.css');
});
由于移动设备和固定设备之间的边界变得流畅,移动浏览器已经很强大,因此检查宽度和用户确认可能是未来的最佳选择(假设在某些情况下宽度仍然很重要)。因为触摸已经转换为鼠标上下。
关于移动移动性,我建议你考虑一下约夫·巴尼亚的想法:
if(typeof window.orientation !== 'undefined'){...}
其他回答
你也可以像下面这样检测它
$.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"));
};
有时,为了显示特定于该设备的内容,需要知道客户使用的是哪个品牌的设备,例如iPhone商店或Android市场的链接。Modernizer非常棒,但它只向您展示浏览器功能,如HTML5或Flash。
以下是我在jQuery中的UserAgent解决方案,为每种设备类型显示不同的类:
/*** sniff the UA of the client and show hidden div's for that device ***/
var customizeForDevice = function(){
var ua = navigator.userAgent;
var checker = {
iphone: ua.match(/(iPhone|iPod|iPad)/),
blackberry: ua.match(/BlackBerry/),
android: ua.match(/Android/)
};
if (checker.android){
$('.android-only').show();
}
else if (checker.iphone){
$('.idevice-only').show();
}
else if (checker.blackberry){
$('.berry-only').show();
}
else {
$('.unknown-device').show();
}
}
此解决方案来自Graphics Maniacshttp://graphicmaniacs.com/note/detecting-iphone-ipod-ipad-android-and-blackberry-browser-with-javascript-and-php/
如果你说的“移动”是指“小屏幕”,我用这个:
var windowWidth = window.screen.width < window.outerWidth ?
window.screen.width : window.outerWidth;
var mobile = windowWidth < 500;
在iPhone上,你会得到一个320的window.screen.width。在Android上,你将得到一个窗口.outerWidth为480(尽管这取决于Android)。iPad和Android平板电脑将返回768这样的数字,这样它们就能像你想要的那样获得完整的视图。
这似乎是一个全面的现代解决方案:
https://github.com/matthewhudson/device.js
它可以检测多个平台,智能手机与平板电脑,以及方向。它还将类添加到BODY标记中,因此检测只发生一次,您可以通过一系列简单的jQuery hasClass函数来读取所使用的设备。
过来看。。。
[免责声明:我与写这封信的人无关。]
我用这个
if(navigator.userAgent.search("mobile")>0 ){
do something here
}