1852

ユーザーがjQueryでモバイルデバイスを使用しているかどうかを検出する方法はありますか? CSS属性に似た@mediaもの?ブラウザーがハンドヘルド デバイス上にある場合は、別のスクリプトを実行したいと思います。

jQuery$.browser関数は、私が探しているものではありません。

4

60 に答える 60

2227

編集者注:ユーザー エージェントの検出は、最新の Web アプリでは推奨される手法ではありません。この事実の確認については、この回答の下のコメントを参照してください。機能検出および/またはメディアクエリを使用して、他の回答のいずれかを使用することをお勧めします。


jQuery を使用する代わりに、単純な JavaScript を使用して検出できます。

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"

注: jQuery v1.9.1$.browserで削除されました。ただし、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;
}
于 2010-08-22T05:26:26.297 に答える
629

私にとって小さいことは美しいので、このテクニックを使用しています:

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 にダミー要素を追加することなく、必要に応じてスマートフォンやタブレットなどのさまざまなデバイスを条件付きで個別にターゲットにできることです。

于 2012-04-28T14:52:56.127 に答える
102

シンプルで効果的なワンライナー:

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

ただし、上記のコードは、タッチスクリーンを備えたラップトップの場合を考慮していません。したがって、 @Julian ソリューションに基づいて、この 2 番目のバージョンを提供します。

function isMobile() {
  try{ document.createEvent("TouchEvent"); return true; }
  catch(e){ return false; }
}
于 2013-11-29T21:14:18.413 に答える
70

jQuery ではありませんが、これを見つけました: http://detectmobilebrowser.com/

JavaScript を含む複数の言語でモバイル ブラウザーを検出するスクリプトを提供します。それはあなたが探しているものに役立つかもしれません。

ただし、jQuery を使用しているため、jQuery.support コレクションに注意する必要がある場合があります。これは、現在のブラウザーの機能を検出するためのプロパティのコレクションです。ドキュメントはこちら: http://api.jquery.com/jQuery.support/

あなたが何を達成しようとしているのか正確にはわからないので、これらのどれが最も役立つかわかりません.

そうは言っても、サーバー側の言語を使用して出力にリダイレクトするか、別のスクリプトを書き込むのが最善の策だと思います(それがオプションの場合)。モバイル ブラウザー x の機能についてはよくわからないため、サーバー側で検出と変更のロジックを実行するのが最も信頼できる方法です。もちろん、サーバー側の言語を使用できない場合、それはすべて議論の余地があります:)

于 2010-08-18T18:02:13.657 に答える
49

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/からのものです。

于 2011-06-09T18:26:17.280 に答える
45

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...
}
于 2012-11-21T13:03:27.217 に答える
29

「モバイル」が「小さな画面」を意味する場合、私はこれを使用します。

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 のような数字を返すので、必要に応じて完全なビューを取得できます。

于 2012-05-11T18:42:22.780 に答える
22

JavaScript の 1 行で:

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

ユーザー エージェントに「Mobi」が含まれており (MDN に従って)、ontouchstart が利用可能な場合、それはモバイル デバイスである可能性があります。

編集: コメントのフィードバックに応じて正規表現コードを更新します。正規表現/mobi/ii を使用すると、大文字と小文字が区別されなくなり、mobi はすべてのモバイル ブラウザーに一致します。https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefoxを参照してください

于 2015-09-28T13:54:55.850 に答える
18

navigator.userAgentすべてのデバイスが実際の OS を公開しているわけではありません。たとえば、私の 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");
}
于 2011-07-08T10:10:33.220 に答える
15

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また、ユーザー エージェントをテストすると、検出された Microsoft モバイル デバイスの範囲が よりも広くなることにも注意してくださいWindows Phone

このSOの質問も参照してください

于 2013-06-26T17:15:37.147 に答える
11

小さなディスプレイについて特に心配していない場合は、幅/高さの検出を使用できます。そのため、幅が特定のサイズを下回ると、モバイル サイトが表示されなくなります。これは完璧な方法ではないかもしれませんが、おそらく複数のデバイスを検出するのが最も簡単でしょう. iPhone 4 (高解像度) 用に特定のものを入れる必要があるかもしれません。

于 2010-08-18T19:46:16.757 に答える
11

If found that just checking navigator.userAgent isn't always reliable. Greater reliability can be achieved by also checking navigator.platform. A simple modification to a previous answer seems to work better:

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ||
   (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform))) {
    // some code...
}
于 2013-01-24T15:10:33.763 に答える
9

素晴らしい答えありがとう。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";
}
于 2012-02-26T20:57:28.450 に答える
9

制御レイヤーを追加するために、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;
}
于 2013-04-18T10:19:21.107 に答える
9

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

これはあなたが探しているものです。

免責事項: 私はこの無料サービスを提供している会社で働いています。

于 2014-03-11T17:20:54.760 に答える
7

この投稿をチェックしてください。タッチ デバイスが検出された場合の対処方法、または 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();
}
于 2011-12-22T22:43:23.223 に答える
6

これを使って:

/**  * 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!');
}
于 2013-06-06T15:01:12.803 に答える
6

すべての回答はユーザーエージェントを使用してブラウザーを検出しますが、ユーザーエージェントに基づくデバイス検出はあまり良い解決策ではありません。タッチデバイスなどの機能を検出する方が良いです (新しい jQuery では削除して代わりに$.browser使用し$.supportます)。

モバイルを検出するには、タッチ イベントを確認できます。

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

JavaScriptを使用して「タッチ スクリーン」デバイスを検出する最良の方法は何ですか?

于 2014-05-06T11:11:46.163 に答える
6

モバイル ブラウザで実行しているかどうかについて、真/偽の回答を得るために使用できる関数を次に示します。はい、それはブラウザ スニッフィングですが、それがまさに必要な場合もあります。

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;
}
于 2011-10-06T16:46:23.777 に答える
4

私はこれを使います

if(navigator.userAgent.search("mobile")>0 ){
         do something here
}
于 2012-05-01T17:03:40.967 に答える
4

これは私のプロジェクトで使用している私のコードです:

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; }
}
于 2013-08-26T18:00:06.967 に答える
4

mobiledetect.netはどうですか?

他のソリューションは基本的すぎるようです。これは軽量の PHP クラスです。User-Agent 文字列を特定の HTTP ヘッダーと組み合わせて使用​​し、モバイル環境を検出します。また、WordPress、Drupal、Joomla、Magento などで利用可能なサードパーティのプラグインを使用して、Mobile Detect を利用することもできます。

于 2015-04-21T16:08:38.870 に答える
3

いくつかの方法を試した後、リストを手動で入力して簡単な 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'){...}
于 2013-09-02T11:13:54.713 に答える
3

これは、包括的で最新のソリューションのようです。

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

複数のプラットフォーム、スマートフォンとタブレット、向きを検出します。また、BODY タグにクラスを追加するため、検出は 1 回だけ行われ、単純な一連の jQuery hasClass 関数を使用して、使用しているデバイスを読み取ることができます。

見てみな...

[免責事項: 私はそれを書いた人とは何の関係もありません。]

于 2014-05-05T10:43:39.957 に答える
2

また、小さなJavaScriptライブラリBowserを使用することをお勧めします。これは、iPhone、Androidなどを含むすべてのブラウザに基づいておりnavigator.userAgent、十分にテストされています。

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');
}
于 2013-02-13T20:11:54.000 に答える
2

ユーザー エージェント文字列を単独で信頼するべきではありません。以下の解決策は、すべての状況で機能します。

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)
于 2016-10-26T13:16:32.617 に答える
2

サーバー側スクリプトを使用して、そこから 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>
于 2012-07-18T15:39:50.373 に答える
2

以下のように検出することもできます

$.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"));
};
于 2013-03-16T16:25:29.313 に答える
2

私はこのソリューションを使用しており、すべてのデバイスで正常に動作します:

if (typeof window.orientation !== "undefined" || navigator.userAgent.indexOf('IEMobile') !== -1) {
   //is_mobile
}
于 2020-03-03T09:44:05.283 に答える
2

追加:

iOS 9.xの一部のバージョンでは、Safari で「iPhone」navigator.userAgentが に表示されず、 に表示されnavigator.platformます。

var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent);
    if(!isMobile){
        isMobile=/iPhone|iPad|iPod/i.test(navigator.platform);
    }
于 2016-01-28T00:41:08.563 に答える
1

チェックアウトhttp://detectmobilebrowsers.com/を含むさまざまな言語でモバイル デバイスを検出するためのスクリプトを提供します。

JavaScript、jQuery、PHP、JSP、Perl、Python、ASP、C#、ColdFusion など

于 2015-11-05T05:12:20.793 に答える
1

モバイル デバイスでタッチ可能なデバイスを理解している場合は、タッチ ハンドラーの存在を確認することで判断できます。

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

jQueryは必要ありません。

于 2018-02-15T15:26:46.247 に答える
1
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();
  }
};

私は過去にこのようなものを使用しました。これは前の応答に似ていますが、特に検出がアニメーションやスクロール イベントなどで使用されている場合は、一致の結果をキャッシュするという点で技術的によりパフォーマンスが高くなります。

于 2011-11-04T15:10:22.980 に答える
0

これらは、私が認識している値のすべてです。他の値を知っている場合は、配列の更新を手伝ってください。

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;
}
于 2016-06-05T17:51:12.973 に答える
-3

ユーザー エージェントをテストする場合、正しい方法は、ユーザー エージェントをテストすることです。つまり、 testnavigator.userAgentです。

これがuser偽物である場合、彼らは当然のことです。その後、システムが Unix であるかtest.isUnix()どうかを心配する必要はありません。

ユーザーが userAgent を変更することも問題ありませんが、そうすると、サイトが適切にレンダリングされるとは思えません。

Microsoft ブラウザーのサポートを提供する場合は、コンテンツの最初の数文字に含まれていることを確認し、作成するすべてのページをテストする必要があります。

要するに...常に標準に合わせてコーディングしてください。次に、現在のバージョンの IE で動作するまでハックします。見栄えがよくなるとは思わないでください。それが GitHub の仕事で、1 億ドルが与えられました。

于 2012-07-14T07:58:54.953 に答える