21 적용형웹사이트
1. 개요
적응형(adaptive) 란 매체별 페이지를 별도로 제작하는 기술이다. 자바스크립트를 사용하여 사용자 접속 환경을 체크후 원하는 페이지로 리디렉션 한다.
2. 응용예제
- 예제
- HTML
- JS
root/index.html
1<!DOCTYPE html>2<html lang="ko">3 <head>4 <meta charset="UTF-8" />5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />6 <title>PC</title>7 </head>8 <body>9 <h1>PC전용페이지</h1>10 <div class="pc">PC</div>11 <div class="mobile">Mobile</div>12 </body>13</html>root/mobile/index.html
1<!DOCTYPE html>2<html lang="ko">3 <head>4 <meta charset="UTF-8" />5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />6 <title>모바일</title>7 </head>8 <body>9 <h1>모바일전용페이지</h1>10 <div class="pc">PC</div>11 <div class="mobile">Mobile</div>12 </body>13</html>사용자의 해상도를 확인하는 방법
1/* https://developer.mozilla.org/ko/docs/Web/API/Window/devicePixelRatio */2if (window.devicePixelRatio > 1) {3 location.href = 'mobile/';4}3. 각 페이지별 이동버튼 추가
pc와 모바일 페이지로 이동하는 버튼을 만들자
- 지시문
- PC페이지 코드
- 모바일페이지 코드
1<!DOCTYPE html>2<html lang="ko">3 <head>4 <meta charset="UTF-8" />5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />6 <title>PC</title>7 </head>8
9 <body>10 <h1>PC전용페이지</h1>11 <button class="mobile">Mobile</button>12 </body>13 <script src="pc.js"></script>14</html>1//모바일 이동버튼 요소 선택2const mobile = document.querySelector('.mobile');3//사용자의 밀도 확인변수4let ratio;5//현재 파일 경로에 mobile 이라는 문자열이 포함되어 있는지 검사 있으면 true 없으면 fasle6let path = location.pathname.split('/').includes('mobile');7//현재 파일 경로 저장8const page = location.href;9
10// 현재 파일경로에 mobile 문자열이 없고 현재 파일 경로와 보고있는 파일경로가 같다면 (pc페이지 확인)11if (!path && location.href === page) {12 //현재 화면 밀도확인13 ratio = window.devicePixelRatio;14 // 밀도가 2보다 크면 모바일로 이동하고 1보다 작거나 같은면 현재 페이지를 연다15 if (ratio > 2) {16 location.href = 'mobile/';17 } else if (ratio <= 1) {18 location.href = page;19 }20}21//모바일 버튼 클릭시 페이지 이동22mobile.onclick = function (e) {23 e.preventDefault();24 location.href = 'mobile/';25};참고
모바일페이지에서 PC로의 이동시 픽셀비율을 확인하게 될 경우 무한루프에 빠지게 되므로 확인하지 않는다. pc이동 버튼 클릭시에 href 값만 변경한다.
1<!DOCTYPE html>2<html lang="ko">3 <head>4 <meta charset="UTF-8" />5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />6 <title>mobile</title>7 </head>8
9 <body>10 <h1>모바일전용페이지</h1>11 <button class="pc">PC</button>12 </body>13 <script src="mobile.js"></script>14</html>1const pc = document.querySelector('.pc');2let path = location.pathname.split('/').includes('mobile');3const page = location.href;4pc.onclick = function (e) {5 e.preventDefault();6 if (path && location.href === page) {7 location.href = '.';8 }9};