有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
你需要控制大小
var is_mobile = false;
$(window).resize(function() {
if ($('#mobileNav').css('display') == 'block') {
is_mobile = true;
}
if (is_mobile == true) {
console.log('is_mobile')
document.addEventListener(
"DOMContentLoaded", () => {
new Mmenu("#mainMenu", {
"offCanvas": {
"position": "right-front"
}
});
}
);
}
}).resize();
其他回答
我建议你结账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();
}
这就是你要找的。
免责声明:我为提供这项免费服务的公司工作。
如果你不特别担心小显示器,你可以使用宽度/高度检测。这样,如果宽度小于一定大小,移动网站就会被抛出。这可能不是完美的方法,但对于多个设备来说,这可能是最容易检测到的。您可能需要为iPhone4(大分辨率)设置一个特定的分辨率。
你也可以像下面这样检测它
$.isIPhone = function(){
return ((navigator.platform.indexOf("iPhone") != -1) || (navigator.platform.indexOf("iPod") != -1));
};
$.isIPad = function (){
return (navigator.platform.indexOf("iPad") != -1);
};
$.isAndroidMobile = function(){
var ua = navigator.userAgent.toLowerCase();
return ua.indexOf("android") > -1 && ua.indexOf("mobile");
};
$.isAndroidTablet = function(){
var ua = navigator.userAgent.toLowerCase();
return ua.indexOf("android") > -1 && !(ua.indexOf("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>
在新版本的chrome(101)解决方案中,使用navigator.platform可能无法运行谷歌支持站点,但有一种更简单的方法来检查设备是否为移动设备。
如果(navigator.userAgentData.mobile==“true”){//移动电话代码console.log('bile');}其他{//PC和笔记本电脑代码console.log(“PC”);}