有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
你不能依赖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");
}
其他回答
这不是jQuery,但我发现了这个:http://detectmobilebrowser.com/
它提供了检测多种语言的移动浏览器的脚本,其中一种是JavaScript。这可能会帮助你找到你想要的东西。
但是,由于您使用的是jQuery,您可能需要了解jQuery.support集合。它是用于检测当前浏览器功能的财产集合。文档位于此处:http://api.jquery.com/jQuery.support/
因为我不知道你到底想做什么,所以我不知道其中哪一个最有用。
尽管如此,我认为最好的选择是使用服务器端语言(如果可以选择的话)重定向或编写不同的脚本到输出。由于您并不真正了解移动浏览器x的功能,因此在服务器端执行检测和更改逻辑将是最可靠的方法。当然,如果您不能使用服务器端语言,所有这些都是一个悬而未决的问题:)
结账http://detectmobilebrowsers.com/它为您提供了多种语言的移动设备检测脚本,包括
JavaScript、jQuery、PHP、JSP、Perl、Python、ASP、C#、ColdFusion等
如果您使用Modernizr,那么很容易使用前面提到的Modernizr.touch。
然而,为了安全起见,我更喜欢使用Moderniz.touch和用户代理测试的组合。
var deviceAgent = navigator.userAgent.toLowerCase();
var isTouchDevice = Modernizr.touch ||
(deviceAgent.match(/(iphone|ipod|ipad)/) ||
deviceAgent.match(/(android)/) ||
deviceAgent.match(/(iemobile)/) ||
deviceAgent.match(/iphone/i) ||
deviceAgent.match(/ipad/i) ||
deviceAgent.match(/ipod/i) ||
deviceAgent.match(/blackberry/i) ||
deviceAgent.match(/bada/i));
if (isTouchDevice) {
//Do something touchy
} else {
//Can't touch this
}
如果您不使用Modernizr,您可以简单地将上面的Modernizr.touch函数替换为(document.documentElement中的“ntouchstart”)
还要注意,测试用户代理iemobile将为您提供比Windows Phone更广泛的检测到的Microsoft移动设备。
另请参阅此SO问题
您还可以使用服务器端脚本并从中设置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>
一种简单有效的内衬:
function isMobile() { return ('ontouchstart' in document.documentElement); }
然而,上述代码没有考虑到带有触摸屏的笔记本电脑的情况。因此,我提供了基于@Julian解决方案的第二个版本:
function isMobile() {
try{ document.createEvent("TouchEvent"); return true; }
catch(e){ return false; }
}