有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
为了增加额外的控制层,我使用HTML5存储来检测它是使用移动存储还是桌面存储。如果浏览器不支持存储,我有一组移动浏览器名称,并将用户代理与阵列中的浏览器进行比较。
这很简单。功能如下:
// Used to detect whether the users browser is an mobile browser
function isMobile() {
///<summary>Detecting whether the browser is a mobile browser or desktop browser</summary>
///<returns>A boolean value indicating whether the browser is a mobile browser or not</returns>
if (sessionStorage.desktop) // desktop storage
return false;
else if (localStorage.mobile) // mobile storage
return true;
// alternative
mobile = ['iphone','ipad','android','blackberry','nokia','opera mini','windows mobile','windows phone','iemobile','tablet','mobi'];
var ua=navigator.userAgent.toLowerCase();
for (var i in mobile) if (ua.indexOf(mobile[i]) > -1) return true;
// nothing found.. assume desktop
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。根据结果,我将进行必要的更改。
navigator.userAgentData.mobile返回[true|false]
我知道这是一个关于这种检测的老问题。
我的解决方案基于滚动条宽度(是否存在)。
//此函数将检查滚动条的宽度//如果滚动条宽度为0px,则为移动设备//函数ismob(){var dv=文档.getElementById('divscr');var sp=文档.getElementById('res');如果(dv.offsetWidth-dv.clientWidth==10){sp.innerHTML=“是移动的”;//返回true;}其他{sp.innerHTML=“它不是移动的”//return false;}//}<!-- 将隐藏的div放在页面-->的开头</div><span id=“res”></span>
有时,为了显示特定于该设备的内容,需要知道客户使用的是哪个品牌的设备,例如iPhone商店或Android市场的链接。Modernizer非常棒,但它只向您展示浏览器功能,如HTML5或Flash。
以下是我在jQuery中的UserAgent解决方案,为每种设备类型显示不同的类:
/*** sniff the UA of the client and show hidden div's for that device ***/
var customizeForDevice = function(){
var ua = navigator.userAgent;
var checker = {
iphone: ua.match(/(iPhone|iPod|iPad)/),
blackberry: ua.match(/BlackBerry/),
android: ua.match(/Android/)
};
if (checker.android){
$('.android-only').show();
}
else if (checker.iphone){
$('.idevice-only').show();
}
else if (checker.blackberry){
$('.berry-only').show();
}
else {
$('.unknown-device').show();
}
}
此解决方案来自Graphics Maniacshttp://graphicmaniacs.com/note/detecting-iphone-ipod-ipad-android-and-blackberry-browser-with-javascript-and-php/
移动设备的具体功能是什么,这意味着你想要不同的行为?
是输入机制(触摸和虚拟键盘与鼠标和物理键盘)、更小的屏幕尺寸还是其他原因?
例如,在CSS4中,您可以为支持触摸的设备使用@media(任何指针:粗糙),而为主要输入为触摸的设备(即,无论是否插入外部键盘,手机和平板电脑)使用@media(指针:粗略)。现代浏览器大多完全支持CSS4。
在JavaScript中,您可以使用Window.matchMedia()测试任何CSS媒体查询(包括上面的查询),如本SO答案中所建议的。(我本来希望现在能有更本土的东西,但找不到任何东西。)