有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在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>
其他回答
function isDeviceMobile(){
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i) && navigator.userAgent.match(/mobile|Mobile/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i)|| navigator.userAgent.match(/BB10; Touch/);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i) || navigator.userAgent.match(/webOS/i) ;
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
return isMobile.any()
}
我知道这个问题有很多答案,但从我所看到的情况来看,没有人能以我的方式解决这个问题。
CSS使用宽度(媒体查询)来确定应用于基于宽度的web文档的样式。为什么不在JavaScript中使用宽度?
例如,在Bootstrap(Mobile First)媒体查询中,存在4个快照/断点:
超小型设备为768像素及以下。小型设备的像素范围从768到991。中等设备的范围从992到1199像素。大型设备为1200像素及以上。
我们也可以使用它来解决JavaScript问题。
首先,我们将创建一个函数,该函数获取窗口大小并返回一个值,该值允许我们查看设备正在查看我们的应用程序的大小:
var getBrowserWidth = function(){
if(window.innerWidth < 768){
// Extra Small Device
return "xs";
} else if(window.innerWidth < 991){
// Small Device
return "sm"
} else if(window.innerWidth < 1199){
// Medium Device
return "md"
} else {
// Large Device
return "lg"
}
};
现在我们已经设置了函数,我们可以调用它并存储值:
var device = getBrowserWidth();
你的问题是
如果浏览器在手持设备上,我希望运行不同的脚本。
现在我们有了设备信息,剩下的就是if语句:
if(device === "xs"){
// Enter your script for handheld devices here
}
下面是CodePen的示例:http://codepen.io/jacob-king/pen/jWEeWG
如果要测试用户代理,正确的方法是测试用户代理(即测试navigator.userAgent)。
如果用户伪造了这一点,他们就不必担心了。如果您测试.isUnix(),则不必担心系统是否为Unix。
作为一个用户,改变userAgent也可以,但如果你这样做了,你不希望站点能够正确呈现。
如果您希望为Microsoft浏览器提供支持,则应确保内容的前几个字符包含并测试您编写的每一页。
要旨始终按照标准进行编码。然后破解它,直到它在当前版本的IE中工作&不要期望它看起来很好。GitHub就是这么做的,他们刚刚拿到了1亿美元。
根据Mozilla浏览器使用用户代理的检测:
总之,我们建议在User Agent中的任何位置查找字符串“Mobi”以检测移动设备。
这样地:
if (/Mobi/.test(navigator.userAgent)) {
// mobile!
}
这将匹配所有常见的移动浏览器用户代理,包括移动Mozilla、Safari、IE、Opera、Chrome等。
Android更新
EricL还建议将Android作为用户代理进行测试,因为平板电脑的Chrome用户代理字符串不包含“Mobi”(但手机版本包含):
if (/Mobi|Android/i.test(navigator.userAgent)) {
// mobile!
}
http://www.w3schools.com/jsref/prop_nav_useragent.asp
按平台名称筛选。
Ex:
x = $( window ).width();
platform = navigator.platform;
alert(platform);
if ( (platform != Ipad) || (x < 768) ) {
}
^^