有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
这就是我所做的:
function checkMobile() {
var os = GetOS();
if (os == "Android OS" || os == "iOS") {
// do what you wanna do
return true
}
}
并重定向我添加location.href=“mobile.website.com”然后添加此body标记
<body onload="checkMobile()"></body>
其他回答
我建议你结账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();
}
这就是你要找的。
免责声明:我为提供这项免费服务的公司工作。
http://www.w3schools.com/jsref/prop_nav_useragent.asp
按平台名称筛选。
Ex:
x = $( window ).width();
platform = navigator.platform;
alert(platform);
if ( (platform != Ipad) || (x < 768) ) {
}
^^
您还可以使用服务器端脚本并从中设置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>
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();
}
};
我过去用过类似的东西。这与之前的响应类似,但它在技术上更具性能,因为它缓存匹配结果,尤其是在动画、滚动事件等中使用检测时。
我建议使用以下字符串组合,以检查是否使用了设备类型。
根据Mozilla文档字符串,建议使用Mobi。但是,如果只使用Mobi,一些旧的平板电脑不会返回真值,因此我们也应该使用Tablet字符串。
同样,为了安全起见,iPad和iPhone字符串也可以用来检查设备类型。
大多数新设备将仅对Mobi字符串返回true。
if (/Mobi|Tablet|iPad|iPhone/.test(navigator.userAgent)) {
// do something
}