簡體   English   中英

如何使用 jQuery 檢測移動設備

[英]How to detect a mobile device using jQuery

jQuery有沒有辦法檢測用戶是否在使用移動設備? 類似於 CSS @media屬性的東西? 如果瀏覽器在手持設備上,我想運行不同的腳本。

jQuery $.browser function 不是我要找的。

編者注:用戶代理檢測不是現代 Web 應用程序的推薦技術。 請參閱此答案下方的評論以確認此事實。 建議使用特征檢測和/或媒體查詢使用其他答案之一。


您可以使用簡單的 JavaScript 來檢測它,而不是使用 jQuery:

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
 // some code..
}

或者您可以將它們結合起來,使其更易於通過 jQuery...

$.browser.device = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));

現在$.browser將為所有上述設備返回"device"

注意: $.browserjQuery v1.9.1上被刪除。 但是您可以通過使用 jQuery 遷移插件代碼來使用它


更徹底的版本:

var isMobile = false; //initiate as false
// device detection
if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent) 
    || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0,4))) { 
    isMobile = true;
}

對我來說,小就是美,所以我正在使用這種技術:

在 CSS 文件中:

/* Smartphones ----------- */
@media only screen and (max-width: 760px) {
  #some-element { display: none; }
}

在 jQuery/JavaScript 文件中:

$( document ).ready(function() {      
    var is_mobile = false;

    if( $('#some-element').css('display')=='none') {
        is_mobile = true;       
    }

    // now I can use is_mobile to run javascript conditionally

    if (is_mobile == true) {
        //Conditional script here
    }
 });

我的目標是讓我的網站“適合移動設備”。 所以我使用 CSS 媒體查詢根據屏幕大小顯示/隱藏元素。

例如,在我的移動版本中,我不想激活 Facebook Like Box,因為它會加載所有這些個人資料圖片和內容。 這對移動訪問者不利。 因此,除了隱藏容器元素之外,我還在 jQuery 代碼塊(上圖)中執行此操作:

if(!is_mobile) {
    (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/pt_PT/all.js#xfbml=1&appId=210731252294735";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
}

您可以在http://lisboaautentica.com上看到它的實際效果

我仍在開發移動版本,所以在撰寫本文時,它仍然看起來不像它應該的那樣。

dekin88更新

有一個內置的 JavaScript API 用於檢測媒體。 而不是使用上述解決方案,只需使用以下內容:

$(function() {      
    let isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;

    if (isMobile) {
        //Conditional script here
    }
 });

瀏覽器支持: http ://caniuse.com/#feat=matchmedia

這種方法的優點在於它不僅更簡單、更短,而且您可以在必要時有條件地分別針對不同的設備(例如智能手機和平板電腦),而無需在 DOM 中添加任何虛擬元素。

根據Mozilla - Browser detection using the user agent

總之,我們建議在用戶代理中的任意位置查找字符串“Mobi”來檢測移動設備。

像這樣:

if (/Mobi/.test(navigator.userAgent)) {
    // mobile!
}

這將匹配所有常見的移動瀏覽器用戶代理,包括移動 Mozilla、Safari、IE、Opera、Chrome 等。

安卓更新

EricL 還建議將Android作為用戶代理進行測試,因為平板電腦的Chrome 用戶代理字符串不包含“Mobi”(但手機版本包含):

if (/Mobi|Android/i.test(navigator.userAgent)) {
    // mobile!
}

一個簡單有效的單線:

function isMobile() { return ('ontouchstart' in document.documentElement); }

但是上面的代碼沒有考慮到帶有觸摸屏的筆記本電腦的情況。 因此,我提供了基於@Julian 解決方案的第二個版本:

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

您想要檢測移動設備所做的事情與 IMO 的“瀏覽器嗅探”概念有點太接近了。 做一些特征檢測可能會好得多。 http://www.modernizr.com/這樣的圖書館可以提供幫助。

例如,移動和非移動之間的界限在哪里? 一天比一天模糊。

它不是 jQuery,但我發現了這個: http ://detectmobilebrowser.com/

它提供腳本來檢測多種語言的移動瀏覽器,其中一種是 JavaScript。 這可能會幫助您找到所需的內容。

但是,由於您使用的是 jQuery,您可能需要了解 jQuery.support 集合。 它是用於檢測當前瀏覽器功能的屬性集合。 文檔在這里: http ://api.jquery.com/jQuery.support/

由於我不知道您到底要完成什么,所以我不知道其中哪一個最有用。

話雖如此,我認為您最好的選擇是使用服務器端語言重定向或編寫不同的腳本到輸出(如果這是一個選項)。 由於您並不真正了解移動瀏覽器 x 的功能,因此在服務器端執行檢測和更改邏輯將是最可靠的方法。 當然,如果您不能使用服務器端語言,那么所有這些都是有爭議的 :)

有時需要知道客戶正在使用哪個品牌的設備,以便顯示特定於該設備的內容,例如指向 iPhone 商店或 Android 市場的鏈接。 Modernizer 很棒,但僅向您展示瀏覽器功能,例如 HTML5 或 Flash。

這是我在 jQuery 中的 UserAgent 解決方案,用於為每種設備類型顯示不同的類:

/*** sniff the UA of the client and show hidden div's for that device ***/
var customizeForDevice = function(){
    var ua = navigator.userAgent;
    var checker = {
      iphone: ua.match(/(iPhone|iPod|iPad)/),
      blackberry: ua.match(/BlackBerry/),
      android: ua.match(/Android/)
    };
    if (checker.android){
        $('.android-only').show();
    }
    else if (checker.iphone){
        $('.idevice-only').show();
    }
    else if (checker.blackberry){
        $('.berry-only').show();
    }
    else {
        $('.unknown-device').show();
    }
}

此解決方案來自 Graphics Maniacs http://graphicmaniacs.com/note/detecting-iphone-ipod-ipad-android-and-blackberry-browser-with-javascript-and-php/

在以下位置找到了解決方案: http ://www.abeautifulsite.net/blog/2011/11/detecting-mobile-devices-with-javascript/。

var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};

然后要驗證它是否是手機,您可以使用以下方法進行測試:

if(isMobile.any()) {
   //some code...
}

如果“移動”是指“小屏幕”,我使用這個:

var windowWidth = window.screen.width < window.outerWidth ?
                  window.screen.width : window.outerWidth;
var mobile = windowWidth < 500;

在 iPhone 上,window.screen.width 為 320。在 Android 上,window.outerWidth 為 480(盡管這可能取決於 Android)。 iPad 和 Android 平板電腦將返回 768 之類的數字,因此它們將獲得您想要的完整視圖。

在一行 javascript 中:

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

如果用戶代理包含“Mobi”(根據 MDN)並且 ontouchstart 可用,那么它很可能是移動設備。

編輯:更新正則表達式代碼以響應評論中的反饋。 使用正則表達式/mobi/i i 使其不區分大小寫,並且 mobi 匹配所有移動瀏覽器。 請參閱https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox

我知道這個問題有很多答案,但據我所知,沒有人以我解決這個問題的方式接近答案。

CSS 使用寬度(媒體查詢)根據寬度確定應用於 Web 文檔的樣式。 為什么不在 JavaScript 中使用寬度?

例如,在 Bootstrap 的(移動優先)媒體查詢中,存在 4 個快照/斷點:

  • 超小型設備為 768 像素及以下。
  • 小型設備的范圍從 768 到 991 像素。
  • 中型設備的范圍從 992 到 1199 像素。
  • 大型設備為 1200 像素及以上。

我們也可以使用它來解決我們的 JavaScript 問題。

首先,我們將創建一個函數來獲取窗口大小並返回一個值,該值允許我們查看正在查看我們的應用程序的設備大小:

var getBrowserWidth = function(){
    if(window.innerWidth < 768){
        // Extra Small Device
        return "xs";
    } else if(window.innerWidth < 991){
        // Small Device
        return "sm"
    } else if(window.innerWidth < 1199){
        // Medium Device
        return "md"
    } else {
        // Large Device
        return "lg"
    }
};

現在我們已經設置了函數,我們可以調用它並存儲值:

var device = getBrowserWidth();

你的問題是

如果瀏覽器在手持設備上,我想運行不同的腳本。

現在我們有了設備信息,剩下的就是一個 if 語句:

if(device === "xs"){
  // Enter your script for handheld devices here 
}

這是 CodePen 的示例: http ://codepen.io/jacob-king/pen/jWEeWG

您不能依賴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");
}

如果您使用Modernizr ,如前所述,使用Modernizr.touch非常容易。

但是,為了安全起見,我更喜歡結合使用Modernizr.touch和用戶代理測試。

var deviceAgent = navigator.userAgent.toLowerCase();

var isTouchDevice = Modernizr.touch || 
(deviceAgent.match(/(iphone|ipod|ipad)/) ||
deviceAgent.match(/(android)/)  || 
deviceAgent.match(/(iemobile)/) || 
deviceAgent.match(/iphone/i) || 
deviceAgent.match(/ipad/i) || 
deviceAgent.match(/ipod/i) || 
deviceAgent.match(/blackberry/i) || 
deviceAgent.match(/bada/i));

if (isTouchDevice) {
        //Do something touchy
    } else {
        //Can't touch this
    }

如果你不使用 Modernizr,你可以簡單地將上面的Modernizr.touch函數替換為('ontouchstart' in document.documentElement)

另請注意,測試用戶代理iemobile將為您提供比Windows Phone更廣泛的檢測到的 Microsoft 移動設備。

另請參閱此 SO 問題

我很驚訝沒有人指出一個不錯的網站: http ://detectmobilebrowsers.com/ 它已經為移動檢測提供了不同語言的現成代碼(包括但不限於):

  • 阿帕奇
  • ASP
  • C#
  • IIS
  • JavaScript
  • NGINX
  • PHP
  • Perl
  • Python
  • 導軌

如果您還需要檢測平板電腦,只需檢查關於部分以獲取其他 RegEx 參數。

Android 平板電腦、iPad、Kindle Fires 和 PlayBook 在設計上無法檢測到。 要添加對平板電腦的支持,請將|android|ipad|playbook|silk添加到第一個正則表達式。

如果發現僅檢查navigator.userAgent並不總是可靠的。 通過檢查navigator.platform可以實現更高的可靠性。 對先前答案的簡單修改似乎效果更好:

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ||
   (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform))) {
    // some code...
}

如果您不是特別擔心小型顯示器,您可以使用寬度/高度檢測。 這樣,如果寬度小於一定大小,移動網站就會被拋出。 這可能不是完美的方法,但它可能是最容易檢測到多個設備的方法。 您可能需要為 iPhone 4(大分辨率)放入一個特定的。

為了添加額外的控制層,我使用 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;
}

我建議你看看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();
}

這就是你要找的。

免責聲明:我為提供這項免費服務的公司工作。

我知道這是關於這種檢測的非常古老的問題。

我的解決方案基於滾動條寬度(是否存在)。

 // this function will check the width of scroller // if scroller width is less than 10px it's mobile device //function ismob() { var dv = document.getElementById('divscr'); var sp=document.getElementById('res'); if (dv.offsetWidth - dv.clientWidth < 10) {sp.innerHTML='Is mobile'; //return true; } else { sp.innerHTML='It is not mobile'; //return false; } //}
 <!-- put hidden div on very begining of page --> <div id="divscr" style="position:fixed;top:0;left:0;width:50px;height:50px;overflow:hidden;overflow-y:scroll;z-index:-1;visibility:hidden;"></div> <span id="res"></span>

很好的答案謝謝。 支持 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
}

查看這篇文章,它提供了一個非常好的代碼片段,用於說明檢測到觸摸設備時的操作或調用 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();
}

用這個:

/**  * jQuery.browser.mobile (http://detectmobilebrowser.com/)  * jQuery.browser.mobile will be true if the browser is a mobile device  **/ (function(a){jQuery.browser.mobile=/android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

然后使用這個:

if(jQuery.browser.mobile)
{
   console.log('You are using a mobile device!');
}
else
{
   console.log('You are not using a mobile device!');
}

所有答案都使用用戶代理來檢測瀏覽器,但基於用戶代理的設備檢測並不是很好的解決方案,更好的是檢測觸摸設備等功能(在新的 jQuery 中,他們刪除$.browser並改用$.support )。

要檢測移動設備,您可以檢查觸摸事件:

function is_touch_device() {
  return 'ontouchstart' in window // works on most browsers 
      || 'onmsgesturechange' in window; // works on ie10
}

取自使用 JavaScript 檢測“觸摸屏”設備的最佳方法是什么?

我建議使用以下字符串組合來檢查是否使用了設備類型。

根據Mozilla 文檔字符串,建議使用Mobi 但是,如果只使用Mobi ,一些舊的 tablet 不會返回 true,因此我們也應該使用Tablet字符串。

同樣,為了安全起見, iPadiPhone字符串也可用於檢查設備類型。

大多數新設備將Mobi字符串返回true

if (/Mobi|Tablet|iPad|iPhone/.test(navigator.userAgent)) {
    // do something
}

我知道這個老問題並且有很多答案,但我認為這個功能很簡單,有助於檢測所有移動設備、平板電腦和計算機瀏覽器,它就像一個魅力。

function Device_Type() 
{
    var Return_Device; 
    if(/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android|iemobile|w3c|acs\-|alav|alca|amoi|audi|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd\-|dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg\-c|lg\-d|lg\-g|lge\-|maui|maxo|midp|mits|mmef|mobi|mot\-|moto|mwbp|nec\-|newt|noki|palm|pana|pant|phil|play|port|prox|qwap|sage|sams|sany|sch\-|sec\-|send|seri|sgh\-|shar|sie\-|siem|smal|smar|sony|sph\-|symb|t\-mo|teli|tim\-|tosh|tsm\-|upg1|upsi|vk\-v|voda|wap\-|wapa|wapi|wapp|wapr|webc|winw|winw|xda|xda\-) /i.test(navigator.userAgent))
    {
        if(/(tablet|ipad|playbook)|(android(?!.*(mobi|opera mini)))/i.test(navigator.userAgent)) 
        {
            Return_Device = 'Tablet';
        }
        else
        {
            Return_Device = 'Mobile';
        }
    }
    else if(/(tablet|ipad|playbook)|(android(?!.*(mobi|opera mini)))/i.test(navigator.userAgent)) 
    {
        Return_Device = 'Tablet';
    }
    else
    {
        Return_Device = 'Desktop';
    }

    return Return_Device;
}

知道TouchEvent僅適用於移動設備,也許最簡單的方法是檢查用戶設備是否可以支持它:

function isMobile() {
  try { 
       document.createEvent("TouchEvent"); 
       return true; 
     }
  catch(e) { 
       return 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;
}

基於http://detectmobilebrowser.com/的簡單函數

function isMobile() {
    var a = navigator.userAgent||navigator.vendor||window.opera;
    return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4));
}
<script>
  function checkIsMobile(){
      if(navigator.userAgent.indexOf("Mobile") > 0){
        return true;
      }else{
        return false;
      }
   }
</script>

如果您使用任何瀏覽器並且嘗試獲取 navigator.userAgent ,那么我們將獲得類似於以下內容的瀏覽器信息

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36

如果你在手機上做同樣的事情,你會得到關注

Mozilla/5.0 (Linux; Android 8.1.0; Pixel Build/OPP6.171019.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.98 Mobile Safari/537.36

每個移動瀏覽器都會有帶有包含“Mobile”的字符串的用戶代理所以我在我的代碼中使用上面的代碼片段來檢查當前的用戶代理是否是 web/mobile。 根據結果​​,我將進行必要的更改。

我用這個

if(navigator.userAgent.search("mobile")>0 ){
         do something here
}

這是我在項目中使用的代碼:

function isMobile() {
 try {
    if(/Android|webOS|iPhone|iPad|iPod|pocket|psp|kindle|avantgo|blazer|midori|Tablet|Palm|maemo|plucker|phone|BlackBerry|symbian|IEMobile|mobile|ZuneWP7|Windows Phone|Opera Mini/i.test(navigator.userAgent)) {
     return true;
    };
    return false;
 } catch(e){ console.log("Error in isMobile"); return false; }
}

mobiledetect.net怎么樣?

其他解決方案似乎太基本了。 這是一個輕量級的 PHP 類。 它使用 User-Agent 字符串結合特定的 HTTP 標頭來檢測移動環境。 您還可以通過使用適用於 WordPress、Drupal、Joomla、Magento 等的任何 3rd 方插件從 Mobile Detect 中受益。

我嘗試了一些方法,然后我決定手動填寫一個列表並進行簡單的 JS 檢查。 最后用戶必須確認。 因為一些檢查給出了假陽性或陰性。

var isMobile = false;
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Opera Mobile|Kindle|Windows Phone|PSP|AvantGo|Atomic Web Browser|Blazer|Chrome Mobile|Dolphin|Dolfin|Doris|GO Browser|Jasmine|MicroB|Mobile Firefox|Mobile Safari|Mobile Silk|Motorola Internet Browser|NetFront|NineSky|Nokia Web Browser|Obigo|Openwave Mobile Browser|Palm Pre web browser|Polaris|PS Vita browser|Puffin|QQbrowser|SEMC Browser|Skyfire|Tear|TeaShark|UC Browser|uZard Web|wOSBrowser|Yandex.Browser mobile/i.test(navigator.userAgent) && confirm('Are you on a mobile device?')) isMobile = true;

現在,如果您想使用 jQuery 來設置 CSS,您可以執行以下操作:

$(document).ready(function() {
  if (isMobile) $('link[type="text/css"]').attr('href', '/mobile.css');
});

由於移動設備和固定設備之間的邊界變得流暢,並且移動瀏覽器已經很強大,因此檢查寬度和用戶確認可能是未來的最佳選擇(假設在某些情況下寬度仍然很重要)。 因為觸摸已經轉換為鼠標上下移動。

關於移動性,我建議你考慮一下Yoav Barnea 的想法

if(typeof window.orientation !== 'undefined'){...}

這似乎是一個全面的現代解決方案:

https://github.com/matthewhudson/device.js

它檢測多個平台、智能手機與平板電腦和方向。 它還將類添加到 BODY 標記,因此檢測只發生一次,您可以使用一系列簡單的 jQuery hasClass 函數來讀取您正在使用的設備。

一探究竟...

[免責聲明:我與寫它的人無關。]

try/catch塊中使用多種檢測技術的 ES6 解決方案

該函數包括創建一個“TouchEvent” ,尋求對“ontouchstart”事件的支持,甚至對mediaQueryList對象進行查詢。

故意地,一些失敗的查詢會拋出一個新的錯誤,因為我們在try/catch塊中,我們可以使用它作為回退來咨詢用戶代理。

我沒有使用測試,在許多情況下它可能會失敗並指出誤報。

它不應該用於任何類型的實際驗證,但在數據量可以“原諒”缺乏精度的分析和統計的一般范圍內,它可能仍然有用。

 const isMobile = ((dc, wd) => { // get browser "User-Agent" or vendor ... see "opera" property in `window` let ua = wd.userAgent || wd.navigator.vendor || wd.opera; try { /** * Creating a touch event ... in modern browsers with touch screens or emulators (but not mobile) does not cause errors. * Otherwise, it will create a `DOMException` instance */ dc.createEvent("TouchEvent"); // check touchStart event (('ontouchstart' in wd) || ('ontouchstart' in dc.documentElement) || wd.DocumentTouch && wd.document instanceof DocumentTouch || wd.navigator.maxTouchPoints || wd.navigator.msMaxTouchPoints) ? void(0) : new Error('failed check "ontouchstart" event'); // check `mediaQueryList` ... pass as modern browsers let mQ = wd.matchMedia && matchMedia("(pointer: coarse)"); // if no have, throw error to use "User-Agent" sniffing test if ( !mQ || mQ.media !== "(pointer: coarse)" || !mQ.matches ) { throw new Error('failed test `mediaQueryList`'); } // if there are no failures the possibility of the device being mobile is great (but not guaranteed) return true; } catch(ex) { // fall back to User-Agent sniffing return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(ua) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[aw])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(ua.substr(0,4)); } })(document, window); // to show result let container = document.getElementById('result'); container.textContent = isMobile ? 'Yes, your device appears to be mobile' : 'No, your device does not appear to be mobile';
 <p id="result"></p>


用於測試用戶代理的正則表達式有點舊,可在不再運行的網站http://mobiledetect.com上找到。

也許有更好的模式,但我不知道。


字體


PS

因為無論是通過檢查功能,還是通過使用正則表達式檢查用戶代理字符串,都無法以100%的准確率進行識別。 上面的代碼片段應僅被視為:“此問題的另一個示例”,以及:“不建議在生產中使用”。

您還可以使用服務器端腳本並從中設置 javascript 變量。

php中的示例

下載http://code.google.com/p/php-mobile-detect/然后設置 javascript 變量。

<script>
//set defaults
var device_type = 'desktop';
</script>

<?php
require_once( 'Mobile_Detect.php');
$detect = new Mobile_Detect();
?>

<script>
device_type="<?php echo ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'mobile') : 'desktop'); ?>";
alert( device_type);
</script>

我還推薦使用小型 JavaScript 庫 Bowser,是的,不是 r。 它基於navigator.userAgent並針對包括 iPhone、Android 等在內的所有瀏覽器進行了很好的測試。

https://github.com/ded/bowser

你可以簡單地說:

if (bowser.msie && bowser.version <= 6) {
  alert('Hello China');
} else if (bowser.firefox){
  alert('Hello Foxy');
} else if (bowser.chrome){
  alert('Hello Silicon Valley');
} else if (bowser.safari){
  alert('Hello Apple Fan');
} else if(bowser.iphone || bowser.android){
  alert('Hello mobile');
}

您也可以像下面這樣檢測它

$.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"));
};
function isDeviceMobile(){
 var isMobile = {
  Android: function() {
      return navigator.userAgent.match(/Android/i) && navigator.userAgent.match(/mobile|Mobile/i);
  },
  BlackBerry: function() {
      return navigator.userAgent.match(/BlackBerry/i)|| navigator.userAgent.match(/BB10; Touch/);
  },
  iOS: function() {
      return navigator.userAgent.match(/iPhone|iPod/i);
  },
  Opera: function() {
      return navigator.userAgent.match(/Opera Mini/i);
  },
  Windows: function() {
      return navigator.userAgent.match(/IEMobile/i) || navigator.userAgent.match(/webOS/i) ;
  },
  any: function() {
      return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
  }
};      
 return isMobile.any()
}

添加:

iOS 9.x的某些版本中,Safari 不會在navigator.platform navigator.userAgent顯示它。

var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent);
    if(!isMobile){
        isMobile=/iPhone|iPad|iPod/i.test(navigator.platform);
    }

不應單獨信任用戶代理字符串。 以下解決方案適用於所有情況。

function isMobile(a) {
  return (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4)));
}

並調用此函數:

isMobile(navigator.userAgent || navigator.vendor || window.opera)

根據您想要檢測移動設備的內容(這意味着此建議並不適合每個人的需求),您可以通過查看 onmouseenter-to-onclick 毫秒差異來實現區分,就像我在這個答案中描述的那樣。

我使用這個解決方案,它在所有設備上都能正常工作:

if (typeof window.orientation !== "undefined" || navigator.userAgent.indexOf('IEMobile') !== -1) {
   //is_mobile
}

你可以像這樣非常簡單地做簡單的事情

(window.screen.width < 700) {
    //The device is a Mobile
} else {
    //The device is a Desktop
}

屏幕可能在具有小分辨率的桌面上或具有較寬分辨率的移動設備上,因此,結合在此問題中找到的兩個答案

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')
}

以下答案改編自https://attacomsian.com/blog/javascript-detect-mobile-device上的答案。

要檢測用戶是否在 JavaScript 中使用移動設備,我們可以使用userAgent屬性。

此屬性是navigator器對象的一部分,由瀏覽器在 HTTP 標頭中發送。 它包含有關瀏覽器名稱、版本和平台的信息。

使用userAgent的值,我們可以使用正則表達式來測試它是否包含一些關鍵字,然后確定設備的類型(移動設備、平板電腦或台式機)。 或者,您還可以將此測試與當前窗口的寬度相結合。

這是一個返回設備類型的函數,用戶當前正在使用:

 function deviceType() { const ua = navigator.userAgent; if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) { return "tablet"; } else if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) { return "mobile"; } return "desktop"; }; console.log(deviceType());

🔑注意:上述解決方案並不總是可靠的 userAgent的值可以很容易地更改。 例如,當我們使用機器人抓取網站時,我們可以傳遞一個完全不同的用戶代理值來隱藏我們的身份。 這將使檢測實際設備類型變得困難。

http://www.w3schools.com/jsref/prop_nav_useragent.asp

按平台名稱過濾。

前任:

x = $( window ).width();

platform = navigator.platform;

alert(platform);

if ( (platform != Ipad) || (x < 768) )  {


} 

^^

結帳http://detectmobilebrowsers.com/它為您提供用於檢測各種語言的移動設備的腳本,包括

JavaScript、jQuery、PHP、JSP、Perl、Python、ASP、C#、ColdFusion 等等

如果您通過移動設備了解可觸摸設備,則可以通過檢查觸摸處理程序的存在來確定它:

let deviceType = (('ontouchstart' in window)
                 || (navigator.maxTouchPoints > 0)
                 || (navigator.msMaxTouchPoints > 0)
                 ) ? 'touchable' : 'desktop';

它不需要jQuery。

這是使用純 JavaScript (es6) 實現的另一個建議

const detectDeviceType = () =>
    /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
        ? 'Mobile'
        : 'Desktop';

detectDeviceType();

利用前面提到的sequielo解決方案,並添加了寬度/高度檢查功能(以避免屏幕旋轉錯誤)。 為了選擇移動視口的最小/最大邊框,我使用此資源https://www.mydevice.io/#compare-devices

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

function deviceType() {
    var width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
    var height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0),screenType;
    if (isMobile()){
        if ((width <= 650 && height <= 900) || (width <= 900 && height <= 650))
            screenType = "Mobile Phone";
        else
            screenType = "Tablet";
    }
    else
        screenType = "Desktop";
  return screenType;
}
var device = {
  detect: function(key) {
    if(this['_'+key] === undefined) {
      this['_'+key] = navigator.userAgent.match(new RegExp(key, 'i'));
    }
    return this['_'+key];
  },
  iDevice: function() {
    return this.detect('iPhone') || this.detect('iPod');
  },
  android: function() {
    return this.detect('Android');
  },
  webOS: function() {
    return this.detect('webOS');
  },
  mobile: function() {
    return this.iDevice() || this.android() || this.webOS();
  }
};

我過去用過這樣的東西。 這與之前的響應類似,但它在技術上更高效,因為它緩存了匹配的結果,尤其是在動畫、滾動事件等中使用檢測時。

這些是我所知道的所有價值。 如果您知道任何其他值,請幫助更新數組。

function ismobile(){
   if(/android|webos|iphone|ipad|ipod|blackberry|opera mini|Windows Phone|iemobile|WPDesktop|XBLWP7/i.test(navigator.userAgent.toLowerCase())) {
       return true;
   }
   else
    return false;
}

你們會做太多的工作。

if (window.screen.availWidth <= 425) {
   // do something
}

您可以通過 JS 在頁面加載時執行此操作。 無需編寫長字符串列表來嘗試捕獲所有內容。 哎呀,你漏了一個! 然后你必須回去改變它/添加它。 更流行的手機尺寸約為 425 寬或更小(縱向模式),平板電腦約為 700 左右,更大的可能是筆記本電腦、台式機或其他更大的設備。 如果您需要移動橫向模式,也許您應該在 Swift 或 Android Studio 中工作,而不是傳統的 Web 編碼。

旁注:發布時這可能不是可用的解決方案,但現在可以使用。

這就是我所做的:

function checkMobile() {
  var os = GetOS();
  if (os == "Android OS" || os == "iOS") {
     // do what you wanna do
     return true
  }
}

並重定向我添加 location.href="mobile.website.com" 然后添加這個 body 標簽

<body onload="checkMobile()"></body>

僅使用matchMedia 的IE10+解決方案:

const isMobile = () => window.matchMedia('(max-width: 700px)').matches

isMobile()返回一個布爾值

在使用navigator.platform的新版本 chrome(101) 解決方案中, 谷歌支持站點可能無法正常工作,但有一種更簡單的方法可以檢查設備是否為移動設備。

 if (navigator.userAgentData.mobile === 'true') { //code for mobile console.log('mobile'); }else { //code for PCs & laptops console.log('PC'); }

你需要控制調整大小

var  is_mobile = false;
        $(window).resize(function() {

            if ($('#mobileNav').css('display') == 'block') {
                is_mobile = true;
            }

            if (is_mobile == true) {

                console.log('is_mobile')
                document.addEventListener(
                    "DOMContentLoaded", () => {
                        new Mmenu("#mainMenu", {
                            "offCanvas": {
                                "position": "right-front"
                            }
                        });
                    }
                );

            }

        }).resize();

MDN 建議使用 Navigator.maxTouchPoints 檢查可用的可觸摸點。 如果 > 0 ,則該設備是可點擊的,並且很可能是手機或平板電腦。 https://developer.mozilla.org/en-US/docs/Web/API/Navigator/maxTouchPoints

如果您使用引導程序,則可以將此元素添加到頁面並檢查其可見性:

      <div id="mobile-detect" class="d-sm-none d-md-block" > </div>


function is_mobile() {
   if( $('#mobile-detect').css('display')=='none') {
       return true;
   }
   return false
}

navigator.userAgentData.mobile 返回 [true|false]

可以檢測 window / 移動瀏覽器是否采用手機屏幕的典型格式,我建議使用 window 高度和寬度(javascript / jquery):

isMobileFormat = ($(window).innerHeight() / $(window).innerWidth()) >= 1.5

移動設備的哪些特定功能意味着您需要不同的行為?

是輸入機制(觸摸和虛擬鍵盤 vs 鼠標和物理鍵盤)、較小的屏幕尺寸還是其他原因?

例如,在 CSS4 中,您可以將@media (any-pointer: coarse)用於支持觸摸的設備,將@media (pointer: coarse)用於主要輸入為觸摸的設備(即手機和平板電腦,無論是否有外部鍵盤)插入)。 現代瀏覽器大多完全支持 CSS4。

在 JavaScript 中,您可以使用Window.matchMedia()來測試任何 CSS 媒體查詢(包括上面的那些),如本 SO 答案中所建議的。 (我本來希望現在能找到更本土的東西,但找不到任何東西。)

我為我的 .NET 應用程序執行此操作。

在我共享_Layout.cshtml頁面中,我添加了這個。

@{
    var isMobileDevice = HttpContext.Current.Request.Browser.IsMobileDevice;
}

<html lang="en" class="@((isMobileDevice)?"ismobiledevice":"")">

然后檢查您網站中的任何頁面(jQuery):

<script>
var isMobile = $('html').hasClass('ismobiledevice');
</script>

只需復制以下函數,它就會返回一個布爾值。 它的正則表達式看起來像標記的答案,但它有一些區別:

const isMobile = () =>
  /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series([46])0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(
    navigator.userAgent
  ) ||
  /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br([ev])w|bumb|bw-([nu])|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do([cp])o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly([-_])|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-([mpt])|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c([- _agpst])|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac([ \-/])|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja([tv])a|jbro|jemu|jigs|kddi|keji|kgt([ /])|klon|kpt |kwc-|kyo([ck])|le(no|xi)|lg( g|\/([klu])|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t([- ov])|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30([02])|n50([025])|n7(0([01])|10)|ne(([cm])-|on|tf|wf|wg|wt)|nok([6i])|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan([adt])|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c([-01])|47|mc|nd|ri)|sgh-|shar|sie([-m])|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel([im])|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c([- ])|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(
    navigator.userAgent.substr(0, 4)
  );

如果要測試用戶代理,正確的方法是測試用戶代理,即測試navigator.userAgent

如果user偽造這一點,他們不會受到應有的關注。 如果你test.isUnix()你不應該擔心系統是否是 Unix。

作為用戶更改 userAgent 也很好,但如果您這樣做,您不希望網站能夠正確呈現。

如果您希望為 Microsoft 瀏覽器提供支持,您應該確保內容的前幾個字符包含並測試您編寫的每個頁面。

底線...始終按照標准進行編碼。 然后破解它,直到它在當前版本的 IE 中工作並且不要期望它看起來不錯。 這就是 GitHub 所做的,他們剛剛獲得了 1 億美元。

用這個

if( screen.width <= 480 ) { 
    // is mobile 
}

粗略,但足以限制加載更大的資源,例如手機與平板電腦/桌面上的視頻文件 - 只需尋找小的寬度或高度來覆蓋兩個方向。 顯然,如果桌面瀏覽器已調整大小,則下面可能會錯誤地檢測到手機,但這對我的用例來說很好/足夠接近。

為什么 480,bcs 根據我找到的關於手機設備尺寸的信息,這看起來是正確的。

if(document.body.clientWidth < 480 || document.body.clientHeight < 480) {
  //this is a mobile device
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM