有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
你也可以像下面这样检测它
$.isIPhone = function(){
return ((navigator.platform.indexOf("iPhone") != -1) || (navigator.platform.indexOf("iPod") != -1));
};
$.isIPad = function (){
return (navigator.platform.indexOf("iPad") != -1);
};
$.isAndroidMobile = function(){
var ua = navigator.userAgent.toLowerCase();
return ua.indexOf("android") > -1 && ua.indexOf("mobile");
};
$.isAndroidTablet = function(){
var ua = navigator.userAgent.toLowerCase();
return ua.indexOf("android") > -1 && !(ua.indexOf("mobile"));
};
其他回答
您可以使用媒体查询来轻松处理它。
isMobile = function(){
var isMobile = window.matchMedia("only screen and (max-width: 760px)");
return isMobile.matches ? true : false
}
我建议你结账http://wurfl.io/
简而言之,如果您导入一个很小的JavaScript文件:
<script type='text/javascript' src="//wurfl.io/wurfl.js"></script>
您将看到一个JSON对象,其外观如下:
{
"complete_device_name":"Google Nexus 7",
"is_mobile":true,
"form_factor":"Tablet"
}
(当然,这是假设您正在使用Nexus 7),您将能够执行以下操作:
if(WURFL.is_mobile) {
//dostuff();
}
这就是你要找的。
免责声明:我为提供这项免费服务的公司工作。
这似乎是一个全面的现代解决方案:
https://github.com/matthewhudson/device.js
它可以检测多个平台,智能手机与平板电脑,以及方向。它还将类添加到BODY标记中,因此检测只发生一次,您可以通过一系列简单的jQuery hasClass函数来读取所使用的设备。
过来看。。。
[免责声明:我与写这封信的人无关。]
看看这篇文章,它提供了一个非常好的代码片段,说明当检测到触摸设备时该怎么做,或者如果调用了touchstart事件,该怎么做:
$(function(){
if(window.Touch) {
touch_detect.auto_detected();
} else {
document.ontouchstart = touch_detect.surface;
}
}); // End loaded jQuery
var touch_detect = {
auto_detected: function(event){
/* add everything you want to do onLoad here (eg. activating hover controls) */
alert('this was auto detected');
activateTouchArea();
},
surface: function(event){
/* add everything you want to do ontouchstart here (eg. drag & drop) - you can fire this in both places */
alert('this was detected by touching');
activateTouchArea();
}
}; // touch_detect
function activateTouchArea(){
/* make sure our screen doesn't scroll when we move the "touchable area" */
var element = document.getElementById('element_id');
element.addEventListener("touchstart", touchStart, false);
}
function touchStart(event) {
/* modularize preventing the default behavior so we can use it again */
event.preventDefault();
}
我为.NET应用程序执行此操作。
在共享的_Layout.cshtml页面中,我添加了这个。
@{
var isMobileDevice = HttpContext.Current.Request.Browser.IsMobileDevice;
}
<html lang="en" class="@((isMobileDevice)?"ismobiledevice":"")">
然后检查站点中的任何页面(jQuery):
<script>
var isMobile = $('html').hasClass('ismobiledevice');
</script>