728x90
01. navigator.userAgent를 이용하여 확인하는 방법
참고 👉 MDN | Navigator: userAgent property
🌵 예시 코드
function isMobile() {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent
);
}
if (isMobile()) {
// 모바일일 경우
} else {
// 모바일 외
}
🌵 예시 코드
function isMobile() {
const userAgent = navigator.userAgent;
if (
userAgent.match(
/iPhone|iPod|Android|Windows CE|BlackBerry|Symbian|Windows Phone|webOS|Opera Mini|Opera Mobi|POLARIS|IEMobile|lgtelecom|nokia|SonyEricsson/i
) != null ||
userAgent.match(/LG|SAMSUNG|Samsung/) != null
) {
return true;
} else {
return false;
}
}
🌵 예시 코드
const isMobile = /Mobi/i.test(window.navigator.userAgent);
// "Mobi" 가 User agent에 포함되어 있으면 모바일
02. JavaScript 터치 이벤트를 이용하여 확인하는 방법
JavaScript의 ontouchstart 이벤트 사용 여부로 모바일 디바이스를 판별합니다.
(터치 스크린이 있는 디바이스에서만 동작합니다.)
const isMobile = (document.documentElement의 'ontouchstart' && navigator.userAgent.match(/Mobi/));
const isTouchDevice = (navigator.maxTouchPoints || 'ontouchstart' in document.documentElement);
03. 스크린 사이즈를 감지하여 확인하는 방법
스크린 사이즈를 확인하여 모바일 디바이스를 감지할 수 있습니다.
🌵 JavaScript
const isMobile = window.matchMedia(
"only screen and (max-width: 768px)"
).matches;
if (isMobile) {
// mobile only
}
🌵 jQuery
if ($(window).width() <= 768) {
// mobile only
}
728x90
'JavaScript' 카테고리의 다른 글
[JavaScript] 마우스 오른쪽 클릭 막는 방법 (0) | 2023.07.10 |
---|---|
[JavaScript] 라디오 버튼 클릭 시 페이지 이동 간단 구현 (0) | 2023.07.07 |
[JavaScript] 시계 구현, 시계 두자리 숫자 표시하기 - padStart() (0) | 2023.07.07 |
[JavaScript] BOM navigator객체 (0) | 2023.07.05 |
[JavaScript] form 유효성 검사 정규식 모음 (0) | 2023.07.05 |