有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
如果您使用Modernizr,那么很容易使用前面提到的Modernizr.touch。
然而,为了安全起见,我更喜欢使用Moderniz.touch和用户代理测试的组合。
var deviceAgent = navigator.userAgent.toLowerCase();
var isTouchDevice = Modernizr.touch ||
(deviceAgent.match(/(iphone|ipod|ipad)/) ||
deviceAgent.match(/(android)/) ||
deviceAgent.match(/(iemobile)/) ||
deviceAgent.match(/iphone/i) ||
deviceAgent.match(/ipad/i) ||
deviceAgent.match(/ipod/i) ||
deviceAgent.match(/blackberry/i) ||
deviceAgent.match(/bada/i));
if (isTouchDevice) {
//Do something touchy
} else {
//Can't touch this
}
如果您不使用Modernizr,您可以简单地将上面的Modernizr.touch函数替换为(document.documentElement中的“ntouchstart”)
还要注意,测试用户代理iemobile将为您提供比Windows Phone更广泛的检测到的Microsoft移动设备。
另请参阅此SO问题
其他回答
我建议使用以下字符串组合,以检查是否使用了设备类型。
根据Mozilla文档字符串,建议使用Mobi。但是,如果只使用Mobi,一些旧的平板电脑不会返回真值,因此我们也应该使用Tablet字符串。
同样,为了安全起见,iPad和iPhone字符串也可以用来检查设备类型。
大多数新设备将仅对Mobi字符串返回true。
if (/Mobi|Tablet|iPad|iPhone/.test(navigator.userAgent)) {
// do something
}
移动设备的具体功能是什么,这意味着你想要不同的行为?
是输入机制(触摸和虚拟键盘与鼠标和物理键盘)、更小的屏幕尺寸还是其他原因?
例如,在CSS4中,您可以为支持触摸的设备使用@media(任何指针:粗糙),而为主要输入为触摸的设备(即,无论是否插入外部键盘,手机和平板电脑)使用@media(指针:粗略)。现代浏览器大多完全支持CSS4。
在JavaScript中,您可以使用Window.matchMedia()测试任何CSS媒体查询(包括上面的查询),如本SO答案中所建议的。(我本来希望现在能有更本土的东西,但找不到任何东西。)
使用了前面提到的sequeelo解决方案,并添加了宽度/高度检查功能(以避免屏幕旋转错误)。为了选择移动视口的最小/最大边界,我使用了这个资源https://www.mydevice.io/#compare-设备
function isMobile() {
try{ document.createEvent("TouchEvent"); return true; }
catch(e){ return false; }
}
function deviceType() {
var width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0),screenType;
if (isMobile()){
if ((width <= 650 && height <= 900) || (width <= 900 && height <= 650))
screenType = "Mobile Phone";
else
screenType = "Tablet";
}
else
screenType = "Desktop";
return screenType;
}
navigator.userAgentData.mobile返回[true|false]
这些都是我所知道的吹嘘。如果您知道任何其他值,请帮助取消数组。
function ismobile(){
if(/android|webos|iphone|ipad|ipod|blackberry|opera mini|Windows Phone|iemobile|WPDesktop|XBLWP7/i.test(navigator.userAgent.toLowerCase())) {
return true;
}
else
return false;
}