JavaScriptでスマホ画面の比率を取得して条件分岐させるTips
画面が特定の比率だった場合、違った処理をさせたいという時の半ば強引なやり方をメモっておきます。
パフォーマンスとか全く考えられていないので、良い方法があったら教えて下さい😅
スマホ画面の比率を取得して分岐
var screenHeight, screenWidth, widthRaito, heightRaito = 0; // スマホ画面の横幅と縦幅を取得 if (window.devicePixelRatio > 0) { screenWidth = window.screen.width * window.devicePixelRatio; screenHeight = window.screen.height * window.devicePixelRatio; } else { screenWidth = window.screen.width; screenHeight = window.screen.width; } // 比率計算・縦横比を比率を変数に格納 function returnRaito(a, b) { for (var i = Math.min(a, b); i > 1; i--) { if (a % i === 0 && b % i === 0) { a = a / i; b = b / i; widthRaito = a; heightRaito = b; } } } // 比率計算を実行 returnRaito(screenWidth, screenHeight); // 分岐処理 if (widthRaito === 2 && heightRaito === 3) { alert('iPhone4の比率(2:3)です。'); }
使いどころは、1画面スクロールを使ったWebサイトとかかな。
縦横比が違うせいでデザインが崩れる場合は、縦積みにするとかフォールバック処理に使えると思う(ノ∀`)