ユーザーがjQueryでモバイルデバイスを使用しているかどうかを検出する方法はありますか? CSS属性に似た@media
もの?ブラウザーがハンドヘルド デバイス上にある場合は、別のスクリプトを実行したいと思います。
jQuery$.browser
関数は、私が探しているものではありません。
ユーザーがjQueryでモバイルデバイスを使用しているかどうかを検出する方法はありますか? CSS属性に似た@media
もの?ブラウザーがハンドヘルド デバイス上にある場合は、別のスクリプトを実行したいと思います。
jQuery$.browser
関数は、私が探しているものではありません。
編集者注:ユーザー エージェントの検出は、最新の 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;
}
私にとって小さいことは美しいので、このテクニックを使用しています:
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 にダミー要素を追加することなく、必要に応じてスマートフォンやタブレットなどのさまざまなデバイスを条件付きで個別にターゲットにできることです。
シンプルで効果的なワンライナー:
function isMobile() { return ('ontouchstart' in document.documentElement); }
ただし、上記のコードは、タッチスクリーンを備えたラップトップの場合を考慮していません。したがって、 @Julian ソリューションに基づいて、この 2 番目のバージョンを提供します。
function isMobile() {
try{ document.createEvent("TouchEvent"); return true; }
catch(e){ return false; }
}
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 の 1 行で:
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を参照してください
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");
}
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
。
小さなディスプレイについて特に心配していない場合は、幅/高さの検出を使用できます。そのため、幅が特定のサイズを下回ると、モバイル サイトが表示されなくなります。これは完璧な方法ではないかもしれませんが、おそらく複数のデバイスを検出するのが最も簡単でしょう. iPhone 4 (高解像度) 用に特定のものを入れる必要があるかもしれません。
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...
}
素晴らしい答えありがとう。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";
}
制御レイヤーを追加するために、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();
}
これはあなたが探しているものです。
免責事項: 私はこの無料サービスを提供している会社で働いています。
この投稿をチェックしてください。タッチ デバイスが検出された場合の対処方法、または 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を使用して「タッチ スクリーン」デバイスを検出する最良の方法は何ですか?
モバイル ブラウザで実行しているかどうかについて、真/偽の回答を得るために使用できる関数を次に示します。はい、それはブラウザ スニッフィングですが、それがまさに必要な場合もあります。
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;
}
私はこれを使います
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 などで利用可能なサードパーティのプラグインを使用して、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 タグにクラスを追加するため、検出は 1 回だけ行われ、単純な一連の jQuery hasClass 関数を使用して、使用しているデバイスを読み取ることができます。
見てみな...
[免責事項: 私はそれを書いた人とは何の関係もありません。]
また、小さなJavaScriptライブラリBowserを使用することをお勧めします。これは、iPhone、Androidなどを含むすべてのブラウザに基づいておりnavigator.userAgent
、十分にテストされています。
あなたは単に言うことができます:
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');
}
ユーザー エージェント文字列を単独で信頼するべきではありません。以下の解決策は、すべての状況で機能します。
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)
サーバー側スクリプトを使用して、そこから 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>
以下のように検出することもできます
$.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"));
};
私はこのソリューションを使用しており、すべてのデバイスで正常に動作します:
if (typeof window.orientation !== "undefined" || navigator.userAgent.indexOf('IEMobile') !== -1) {
//is_mobile
}
追加:
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);
}
チェックアウト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は必要ありません。
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;
}
ユーザー エージェントをテストする場合、正しい方法は、ユーザー エージェントをテストすることです。つまり、 testnavigator.userAgent
です。
これがuser
偽物である場合、彼らは当然のことです。その後、システムが Unix であるかtest.isUnix()
どうかを心配する必要はありません。
ユーザーが userAgent を変更することも問題ありませんが、そうすると、サイトが適切にレンダリングされるとは思えません。
Microsoft ブラウザーのサポートを提供する場合は、コンテンツの最初の数文字に含まれていることを確認し、作成するすべてのページをテストする必要があります。
要するに...常に標準に合わせてコーディングしてください。次に、現在のバージョンの IE で動作するまでハックします。見栄えがよくなるとは思わないでください。それが GitHub の仕事で、1 億ドルが与えられました。