有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
这似乎是一个全面的现代解决方案:
https://github.com/matthewhudson/device.js
它可以检测多个平台,智能手机与平板电脑,以及方向。它还将类添加到BODY标记中,因此检测只发生一次,您可以通过一系列简单的jQuery hasClass函数来读取所使用的设备。
过来看。。。
[免责声明:我与写这封信的人无关。]
其他回答
您可以使用媒体查询来轻松处理它。
isMobile = function(){
var isMobile = window.matchMedia("only screen and (max-width: 760px)");
return isMobile.matches ? true : false
}
这里有一个函数,您可以使用它来获得关于您是否在移动浏览器上运行的正确/错误答案。是的,这是浏览器嗅探,但有时这正是您需要的。
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;
}
我为.NET应用程序执行此操作。
在共享的_Layout.cshtml页面中,我添加了这个。
@{
var isMobileDevice = HttpContext.Current.Request.Browser.IsMobileDevice;
}
<html lang="en" class="@((isMobileDevice)?"ismobiledevice":"")">
然后检查站点中的任何页面(jQuery):
<script>
var isMobile = $('html').hasClass('ismobiledevice');
</script>
仅使用matchMedia的IE10+解决方案:
const isMobile = () => window.matchMedia('(max-width: 700px)').matches
isMobile()返回布尔值
你不能依赖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");
}