有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
如果发现仅检查navigator.userAgent并不总是可靠的。还可以通过检查navigator.platform来实现更高的可靠性。对先前答案的简单修改似乎效果更好:
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ||
(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform))) {
// some code...
}
其他回答
你不能依赖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");
}
这里有一个函数,您可以使用它来获得关于您是否在移动浏览器上运行的正确/错误答案。是的,这是浏览器嗅探,但有时这正是您需要的。
function is_mobile() {
var agents = ['android', 'webos', 'iphone', 'ipad', 'blackberry'];
for(i in agents) {
if(navigator.userAgent.match('/'+agents[i]+'/i')) {
return true;
}
}
return false;
}
很好的回答,谢谢。支持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";
}
如果你说的“移动”是指“小屏幕”,我用这个:
var windowWidth = window.screen.width < window.outerWidth ?
window.screen.width : window.outerWidth;
var mobile = windowWidth < 500;
在iPhone上,你会得到一个320的window.screen.width。在Android上,你将得到一个窗口.outerWidth为480(尽管这取决于Android)。iPad和Android平板电脑将返回768这样的数字,这样它们就能像你想要的那样获得完整的视图。
我很惊讶没有人指出一个好的网站:http://detectmobilebrowsers.com/它已经为移动检测准备好了不同语言的代码(包括但不限于):
阿帕奇ASP软件C类#IIS公司JavaScript发动机发动机PHP文件Perl语言蟒蛇轨道
如果您也需要检测平板电脑,只需查看“关于”部分以获取其他RegEx参数。
Android平板电脑、iPad、Kindle Fires和PlayBook未被设计要添加对平板电脑的支持,请将|android | ipad | playbook | silk添加到第一个正则表达式。