Javascriptでデバイス判定をして、viewportを変更する方法

デバイス判定

静的HTMLでホームページを制作する際には、Javascriptでデバイス判定をする方法を採用しています。

タブレットのviewportを変更して、PCを縮小表示する方法を紹介します。

headタグ内の出来るだけ上の方に

<script>
			var getDevice = (function(){
				var ua = navigator.userAgent;
				if(ua.indexOf('iPhone') > 0 || ua.indexOf('iPod') > 0 || ua.indexOf('Android') > 0 && ua.indexOf('Mobile') > 0){
					return 'sp';
				}else if(ua.indexOf('iPad') > 0 || ua.indexOf('Android') > 0){
					return 'tab';
				}else{
					return 'other';
				}
			})();

			if( getDevice == 'sp' ){
				document.write('<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">');
			}else if( getDevice == 'tab' ){
				document.write('<meta name="viewport" content="width=1280">');
			}else if( getDevice == 'other' ){
				document.write('<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">');
			}

</script>

と記述すればタブレットのみ、<meta name=”viewport” content=”width=1280″>が出力され、PCの縮小表示ができます。

確認は実機でないとできないので、注意してください。

Recruit

私たちは共に働く仲間を求めています。Web制作・広告運用・SEO対策・マーケティング・Web解析・メディア運用・ライティング・Webサービス開発が主な業務です。

PartnerShip

Web制作会社・広告代理店・デザイン会社・コンサルティング会社様

パートナー提携はコチラから

Contact

平日 10:00 - 19:00

TEL 06-6125-5439

無料相談

お問合せ

お見積もり