有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
所有答案都使用用户代理来检测浏览器,但基于用户代理的设备检测不是很好的解决方案,最好是检测触摸设备等功能(在新的jQuery中,他们删除了$.browser,改用$.support)。
要检测移动设备,您可以检查触摸事件:
function is_touch_device() {
return 'ontouchstart' in window // works on most browsers
|| 'onmsgesturechange' in window; // works on ie10
}
摘自使用JavaScript检测“触摸屏”设备的最佳方法是什么?
其他回答
这似乎是一个全面的现代解决方案:
https://github.com/matthewhudson/device.js
它可以检测多个平台,智能手机与平板电脑,以及方向。它还将类添加到BODY标记中,因此检测只发生一次,您可以通过一系列简单的jQuery hasClass函数来读取所使用的设备。
过来看。。。
[免责声明:我与写这封信的人无关。]
根据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!
}
在新版本的chrome(101)解决方案中,使用navigator.platform可能无法运行谷歌支持站点,但有一种更简单的方法来检查设备是否为移动设备。
如果(navigator.userAgentData.mobile==“true”){//移动电话代码console.log('bile');}其他{//PC和笔记本电脑代码console.log(“PC”);}
<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。根据结果,我将进行必要的更改。
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()
}