有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。

jQuery$.browser函数不是我想要的。


当前回答

在新版本的chrome(101)解决方案中,使用navigator.platform可能无法运行谷歌支持站点,但有一种更简单的方法来检查设备是否为移动设备。

如果(navigator.userAgentData.mobile==“true”){//移动电话代码console.log('bile');}其他{//PC和笔记本电脑代码console.log(“PC”);}

其他回答

在一行javascript中:

var isMobile = ('ontouchstart' in document.documentElement && /mobi/i.test(navigator.userAgent));

如果用户代理包含“Mobi”(根据MDN)并且ontouchstart可用,那么它很可能是一个移动设备。

EDIT:根据评论中的反馈更新正则表达式代码。使用regex/mobi/i,i不区分大小写,mobi匹配所有移动浏览器。看见https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox

如果要测试用户代理,正确的方法是测试用户代理(即测试navigator.userAgent)。

如果用户伪造了这一点,他们就不必担心了。如果您测试.isUnix(),则不必担心系统是否为Unix。

作为一个用户,改变userAgent也可以,但如果你这样做了,你不希望站点能够正确呈现。

如果您希望为Microsoft浏览器提供支持,则应确保内容的前几个字符包含并测试您编写的每一页。

要旨始终按照标准进行编码。然后破解它,直到它在当前版本的IE中工作&不要期望它看起来很好。GitHub就是这么做的,他们刚刚拿到了1亿美元。

我建议你结账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();
}

这就是你要找的。

免责声明:我为提供这项免费服务的公司工作。

这里有一个函数,您可以使用它来获得关于您是否在移动浏览器上运行的正确/错误答案。是的,这是浏览器嗅探,但有时这正是您需要的。

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;
}

为了增加额外的控制层,我使用HTML5存储来检测它是使用移动存储还是桌面存储。如果浏览器不支持存储,我有一组移动浏览器名称,并将用户代理与阵列中的浏览器进行比较。

这很简单。功能如下:

// Used to detect whether the users browser is an mobile browser
function isMobile() {
    ///<summary>Detecting whether the browser is a mobile browser or desktop browser</summary>
    ///<returns>A boolean value indicating whether the browser is a mobile browser or not</returns>

    if (sessionStorage.desktop) // desktop storage 
        return false;
    else if (localStorage.mobile) // mobile storage
        return true;

    // alternative
    mobile = ['iphone','ipad','android','blackberry','nokia','opera mini','windows mobile','windows phone','iemobile','tablet','mobi']; 
    var ua=navigator.userAgent.toLowerCase();
    for (var i in mobile) if (ua.indexOf(mobile[i]) > -1) return true;

    // nothing found.. assume desktop
    return false;
}