有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
使用此
if( screen.width <= 480 ) {
// is mobile
}
其他回答
我建议使用以下字符串组合,以检查是否使用了设备类型。
根据Mozilla文档字符串,建议使用Mobi。但是,如果只使用Mobi,一些旧的平板电脑不会返回真值,因此我们也应该使用Tablet字符串。
同样,为了安全起见,iPad和iPhone字符串也可以用来检查设备类型。
大多数新设备将仅对Mobi字符串返回true。
if (/Mobi|Tablet|iPad|iPhone/.test(navigator.userAgent)) {
// do something
}
你不能依赖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");
}
如果使用引导,可以将此元素添加到页面并检查其可见性:
<div id="mobile-detect" class="d-sm-none d-md-block" > </div>
function is_mobile() {
if( $('#mobile-detect').css('display')=='none') {
return true;
}
return false
}
<script>
function checkIsMobile(){
if(navigator.userAgent.indexOf("Mobile") > 0){
return true;
}else{
return false;
}
}
</script>
如果您转到任何浏览器,并且尝试获取navigator.userAgent,那么我们将获得如下浏览器信息
Mozilla/5.0(Macintosh;Intel Mac OS X 10_13_1)AppleWebKit/537.36(KHTML,类似Gecko)Chrome/64.0.3282.186 Safari/537.36
如果你在手机上做同样的事情,你会得到关注
Mozilla/5.0(Linux;Android 8.1.0;Pixel Build/OOP6.171019.012)AppleWebKit/537.36(KHTML,类似Gecko)Chrome/61.0.3163.98 Mobile Safari/537.36
每个移动浏览器都会有useragent,其字符串包含“mobile”,所以我在代码中使用上面的代码片段来检查当前的用户agent是否是web/mobile。根据结果,我将进行必要的更改。
您还可以使用服务器端脚本并从中设置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>