我正在寻找一个函数,返回一个布尔值,如果用户正在使用移动浏览器与否。

我知道我可以使用导航器。userAgent并使用regex编写该函数,但是用户代理对于不同的平台来说太复杂了。我怀疑匹配所有可能的设备是否容易,我认为这个问题已经解决了很多次,所以应该有某种完整的解决方案来完成这样的任务。

我正在看这个网站,但不幸的是,脚本是如此神秘,我不知道如何使用它为我的目的,这是创建一个返回true/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
    var mobile = ['iphone','ipad','android','blackberry','nokia','opera mini','windows mobile','windows phone','iemobile']; 
    for (var i in mobile) if (navigator.userAgent.toLowerCase().indexOf(mobile[i].toLowerCase()) > 0) return true;

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

其他回答

检测手机或平板设备的一个好方法是查看浏览器是否可以创建触摸事件。

简单JavaScript代码:

function isMobile() {
   try{ document.createEvent("TouchEvent"); return true; }
   catch(e){ return false; }
}

if (isMobile()) {
   # do whatever you wanna do!
}

这对我来说效果很好,但是包含触摸屏的笔记本电脑设备可能会有一个问题。

我不确定触屏笔记本电脑是否会被视为移动设备,因为我还没有测试过。

我通常发现,检查只在移动视图中可见的特定元素(比如汉堡图标)的可见性这一更简单的方法效果很好,而且比依赖非常复杂的正则表达式安全得多。这将很难测试100%的工作。

function isHidden(el) {
   return (el.offsetParent === null);
}

我遇到过一些情况,上面的答案对我不起作用。所以我想到了这个。可能对某人有帮助。

if(/iPhone|iPad|iPod|Android|webOS|BlackBerry|Windows Phone/i.test(navigator.userAgent)
 || screen.availWidth < 480){
//code for mobile
}

这取决于您的用例。如果你专注于屏幕使用屏幕。availWidth,或者你可以使用document.body. clientwidth如果你想基于document进行渲染。

我搜索了Replit的代码(因为它在网站上到处都是错误),直到我看到:

(function (isTouchDevice) {
      if (!isTouchDevice) return;
      var isTouchClass = 'is-touch-device';
      var docElement = document.documentElement;
      docElement.className = docElement.className ? [docElement.className, isTouchClass].join(' ') : isTouchClass;
    })(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch);

所以我把它修改成这样:

function isTouchDevice() {
    if (!(("ontouchstart" in window) || (window.DocumentTouch && document instanceof DocumentTouch))) {
        return false
    }
    return true
}

来自不同用户代理的值:

Mozilla/5.0 (Windows NT 10.0;Win64;x64) AppleWebKit/537.36 (KHTML,像壁虎)Chrome/103.0.0.0 Safari/537.36: false Mozilla / 5.0 (Linux;Android 10;小米A2) AppleWebKit/537.36 (KHTML,像壁虎)Chrome/105.0.0.0移动Safari/537.36: true

功能检测比试图弄清楚你在使用哪个设备要好得多,而且很难跟上新设备的步伐,像Modernizr这样的库可以让你知道某个特定功能是否可用。