有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
我建议你结账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();
}
这就是你要找的。
免责声明:我为提供这项免费服务的公司工作。
其他回答
看看这篇文章,它提供了一个非常好的代码片段,说明当检测到触摸设备时该怎么做,或者如果调用了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();
}
很好的回答,谢谢。支持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";
}
您可以使用媒体查询来轻松处理它。
isMobile = function(){
var isMobile = window.matchMedia("only screen and (max-width: 760px)");
return isMobile.matches ? true : false
}
为了检测窗口/移动浏览器是否为手机屏幕的典型格式,我建议使用窗口高度和宽度(javascript/jquery):
isMobileFormat = ($(window).innerHeight() / $(window).innerWidth()) >= 1.5
屏幕可能位于分辨率较小的桌面上,也可能位于分辨率较宽的手机上,因此,结合本问题中的两个答案
const isMobile = window.matchMedia("only screen and (max-width: 760px)");
if (/Mobi|Tablet|iPad|iPhone/i.test(navigator.userAgent) || isMobile.matches) {
console.log('is_mobile')
}