programing

jQuery를 사용하여 모바일 장치를 검색하는 방법

minecode 2022. 10. 31. 21:23
반응형

jQuery를 사용하여 모바일 장치를 검색하는 방법

?Query에서 사용자가 모바일 디바이스를 사용하고 있는지 여부를 검출하는 방법이 있습니까? CSS와 것@media? 디바이스 상에 .브라우저가 핸드헬드 기기에 있는 경우 다른 스크립트를 실행하고 싶습니다.

$.browser을 사용법

편집자 주의: 사용자 에이전트 탐지는 최신 웹 앱에 권장되지 않습니다.이 사실의 확인에 대해서는, 이하의 코멘트를 참조해 주세요.기능 검출 및/또는 미디어 쿼리를 사용하여 다른 응답 중 하나를 사용하는 것이 좋습니다.


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"의 경우

★★★★★★$.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 Media Query를 사용하여 화면 크기에 따라 요소를 표시하거나 숨깁니다.

예를 들어 모바일 버전에서는 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/ #match=matchmedia

DOM에 더미 요소를 추가하지 않고 스마트폰이나 태블릿 등 다른 기기를 조건부로 공략할 수 있는 것이 장점이다.

Mozilla - 사용자 에이전트를 사용한 브라우저 탐지:

요약하면 모바일 디바이스를 검출하기 위해 사용자 에이전트 내에서 "Mobi" 문자열을 찾을 것을 권장합니다.

다음과 같이 합니다.

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

이는 모바일 Mozilla, Safari, IE, Opera, Chrome 등을 포함한 모든 일반적인 모바일 브라우저 사용자 에이전트와 일치합니다.

Android용 업데이트

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

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

"mobile"이 "small screen"을 의미한다면 다음과 같이 사용합니다.

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

iPhone에서는 window.screen이 표시됩니다.폭 320Android에서는 창이 나타납니다.외부 폭은 480(단, Android에 따라 다를 수 있음)입니다.iPad와 Android 태블릿은 768과 같은 숫자를 반환하므로 원하는 대로 전체 화면을 볼 수 있습니다.

javascript의 한 줄:

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

사용자 에이전트에 Mobi(MDN에 따라)가 포함되어 온터치스타트를 사용할 수 있는 경우 모바일 디바이스일 가능성이 높습니다.

편집: 코멘트 피드백에 따라 regex 코드를 업데이트합니다./mobi/ii는 대소문자를 구분하지 않으며, mobi는 모든 모바일 브라우저와 일치합니다.https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox 를 참조해 주세요.

이 질문에는 많은 답이 있다는 것을 알지만, 내가 본 바로는 아무도 이 문제를 해결하는 방법에 접근하지 않는다.

CSS는 너비(미디어 조회)를 사용하여 너비에 따라 웹 문서에 적용되는 스타일을 결정합니다.JavaScript에서 width를 사용하는 이유는 무엇입니까?

예를 들어 Bootstrap의 (모바일 우선) 미디어 쿼리에는 4개의 스냅/브레이크 포인트가 있습니다.

  • Extra Small Devices는 768픽셀 이하입니다.
  • 소형 디바이스의 범위는 768 ~991 픽셀입니다
  • 중형 디바이스의 범위는 992 ~1199 픽셀입니다
  • Large Device는 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모든 디바이스가 실제 OS를 공개하는 것은 아닙니다.예를 들어 HTC에서는 설정에 따라 달라집니다("모바일 버전 사용" 온/오프).http://my.clockodo.com에서는 단순히screen.width이치노안드로이드】【안드로이드】【안드로이드】.userAgent agentagent음 。

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앞서 말한 바와 같이

저는 ,, 음, 음, 음, 다, 다, 음, 음, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, however,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 질문도 참조해 주세요.

아무도 좋은 사이트를 지적하지 않은 것에 놀랐습니다.http://detectmobilebrowsers.com/ 모바일 검출용 코드를 다른 언어로 작성했습니다(이에 한정되지 않습니다).

  • 아파치
  • ASP
  • C#
  • IIS
  • 자바스크립트
  • NGINX
  • PHP
  • 파이썬
  • 레일

태블릿도 검출할 필요가 있는 경우는, 「About(정보)」섹션에서 추가의 RegEx 파라미터를 확인해 주세요.

안드로이드 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★에 대한 하려면 , 「 」를 합니다.|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 파일을 Import하는 경우:

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

이것이 당신이 찾고 있는 것입니다.

면책사항:저는 이 무료 서비스를 제공하는 회사에서 일하고 있습니다.

좋은 답변입니다. 감사합니다.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";
}

이런 종류의 탐지에 대한 아주 오래된 질문인 거 알아요.

이 솔루션은 스크롤러 폭(존재 여부)을 기반으로 합니다.

// 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>

미디어 쿼리를 사용하여 쉽게 처리할 수 있습니다.

isMobile = function(){
    var isMobile = window.matchMedia("only screen and (max-width: 760px)");
    return isMobile.matches ? true : false
}

투고를 확인해 주세요.터치 디바이스가 검출되었을 때의 대처법이나, 터치 스타트 이벤트가 호출되었을 경우의 대처법에 대해, 매우 알기 쉬운 코드 스니펫을 제공하고 있습니다.

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

다음은 모바일 브라우저에서 실행 중인지 여부에 대한 참/거짓 답변을 얻기 위해 사용할 수 있는 기능입니다.네, 브라우저의 감시가 가능하지만, 경우에 따라서는 이것이 바로 필요한 것입니다.

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

사용방법:

/**  * 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스트링도.

안전한 쪽에 경우, 한 쪽에 있는 경우iPad ★★★★★★★★★★★★★★★★★」iPhone스트링을 사용하여 디바이스 유형을 확인할 수도 있습니다.

은, 「귀환」을 합니다.true★★★★★★에Mobi스트링만.

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

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>

브라우저가 있고 네비게이터를 얻으려고 하면 다음과 같은 브라우저 정보를 얻을 수 있습니다.

Mozilla/5.0 (Macintosh, 인텔 Mac OS X 10_13_1) Apple WebKit/537.36 (KHTML, Gecko 등) Chrome/64.0.3282.186 Safari/537.36

모바일에서도 마찬가지입니다.

Mozilla/5.0 (Linux; Android 8.1.0; 픽셀 빌드/OPP6.171019.012) AppleWebKit/537.36 (KHTML, Gecko 등) Chrome/61.0.3163.98 모바일 사파리/537.36

모든 모바일 브라우저에는 "Mobile"을 포함하는 문자열이 포함된 사용자 에이전트가 있습니다. 그래서 현재 사용자 에이전트가 웹/모바일인지 확인하기 위해 코드에 위의 스니펫을 사용하고 있습니다.결과에 따라 필요한 변경을 하게 됩니다.

나는 이것을 사용한다.

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

mobiledetect.net은 어떻습니까?

다른 솔루션은 너무 기본적인 것 같습니다.이것은 경량 PHP 클래스입니다.User-Agent 문자열을 특정 HTTP 헤더와 결합하여 모바일 환경을 탐지합니다.또한 WordPress, Drupal, Joomla, Magento 등 서드파티 플러그인을 사용하여 Mobile Detect의 이점을 누릴 수 있습니다.

언급URL : https://stackoverflow.com/questions/3514784/how-to-detect-a-mobile-device-using-jquery

반응형