有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
添加:
在某些版本的iOS 9.x中,Safari不会在navigator.userAgent中显示“iPhone”,而是在navigater.platform中显示。
var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent);
if(!isMobile){
isMobile=/iPhone|iPad|iPod/i.test(navigator.platform);
}
其他回答
<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。根据结果,我将进行必要的更改。
http://www.w3schools.com/jsref/prop_nav_useragent.asp
按平台名称筛选。
Ex:
x = $( window ).width();
platform = navigator.platform;
alert(platform);
if ( (platform != Ipad) || (x < 768) ) {
}
^^
这不是jQuery,但我发现了这个:http://detectmobilebrowser.com/
它提供了检测多种语言的移动浏览器的脚本,其中一种是JavaScript。这可能会帮助你找到你想要的东西。
但是,由于您使用的是jQuery,您可能需要了解jQuery.support集合。它是用于检测当前浏览器功能的财产集合。文档位于此处:http://api.jquery.com/jQuery.support/
因为我不知道你到底想做什么,所以我不知道其中哪一个最有用。
尽管如此,我认为最好的选择是使用服务器端语言(如果可以选择的话)重定向或编写不同的脚本到输出。由于您并不真正了解移动浏览器x的功能,因此在服务器端执行检测和更改逻辑将是最可靠的方法。当然,如果您不能使用服务器端语言,所有这些都是一个悬而未决的问题:)
很好的回答,谢谢。支持Windows phone和Zune的小改进:
if (navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/webOS/i) ||
navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPad/i) ||
navigator.userAgent.match(/iPod/i) ||
navigator.userAgent.match(/BlackBerry/) ||
navigator.userAgent.match(/Windows Phone/i) ||
navigator.userAgent.match(/ZuneWP7/i)
) {
// some code
self.location = "top.htm";
}
为了增加额外的控制层,我使用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;
}