有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。

jQuery$.browser函数不是我想要的。


当前回答

您还可以使用服务器端脚本并从中设置javascript变量。

php中的示例

下载http://code.google.com/p/php-mobile-detect/然后设置javascript变量。

<script>
//set defaults
var device_type = 'desktop';
</script>

<?php
require_once( 'Mobile_Detect.php');
$detect = new Mobile_Detect();
?>

<script>
device_type="<?php echo ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'mobile') : 'desktop'); ?>";
alert( device_type);
</script>

其他回答

仅使用matchMedia的IE10+解决方案:

const isMobile = () => window.matchMedia('(max-width: 700px)').matches

isMobile()返回布尔值

结账http://detectmobilebrowsers.com/它为您提供了多种语言的移动设备检测脚本,包括

JavaScript、jQuery、PHP、JSP、Perl、Python、ASP、C#、ColdFusion等

在以下位置找到解决方案: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...
}

我很惊讶没有人指出一个好的网站:http://detectmobilebrowsers.com/它已经为移动检测准备好了不同语言的代码(包括但不限于):

阿帕奇ASP软件C类#IIS公司JavaScript发动机发动机PHP文件Perl语言蟒蛇轨道

如果您也需要检测平板电脑,只需查看“关于”部分以获取其他RegEx参数。

Android平板电脑、iPad、Kindle Fires和PlayBook未被设计要添加对平板电脑的支持,请将|android | ipad | playbook | silk添加到第一个正则表达式。

我建议你结账http://wurfl.io/

简而言之,如果您导入一个很小的JavaScript文件:

<script type='text/javascript' src="//wurfl.io/wurfl.js"></script>

您将看到一个JSON对象,其外观如下:

{
 "complete_device_name":"Google Nexus 7",
 "is_mobile":true,
 "form_factor":"Tablet"
}

(当然,这是假设您正在使用Nexus 7),您将能够执行以下操作:

if(WURFL.is_mobile) {
    //dostuff();
}

这就是你要找的。

免责声明:我为提供这项免费服务的公司工作。