18.

【Vue.js】画面サイズの取得方法

編集
この記事の要点
  • JavaScript で画面サイズを取得する 4 つの座標
  • window.innerWidth/innerHeight: ブラウザのビューポートサイズ
  • document.documentElement.clientWidth/Height: スクロールバーを除く幅
  • screen.width/height: モニターサイズ
  • element.offsetWidth/offsetHeight: 個別要素サイズ

 

各種サイズの違い

取得方法含むもの例 (フル HD)
window.innerWidthビューポート(スクロールバー含む)1920
window.innerHeightビューポートの高さ987 (タブ・URL バー除く)
window.outerWidthブラウザウィンドウ全体(含チタンバー)1920
window.outerHeightウィンドウ全体の高さ1080
document.documentElement.clientWidthビューポート(スクロールバー除く)1903
document.documentElement.clientHeight同上の高さ987
document.documentElement.scrollWidthドキュメント全幅(スクロール時の総幅)1920
document.documentElement.scrollHeightドキュメント全高(スクロール総高)5000
screen.widthモニター幅1920
screen.heightモニター高(タスクバー含む)1080
screen.availWidth使用可能幅(タスクバー除く)1920
screen.availHeight同上の高さ1040 (タスクバー 40px 除く)

基本的な使い方

// ビューポートサイズ (もっとも一般的)
const w = window.innerWidth;
const h = window.innerHeight;
console.log(`Viewport: ${w} x ${h}`);

// スクロールバー除く
const cw = document.documentElement.clientWidth;
const ch = document.documentElement.clientHeight;

// モニター
const sw = screen.width;
const sh = screen.height;

// デバイスピクセル比 (Retina 等)
const dpr = window.devicePixelRatio;  // 1, 2, 3 等
console.log(`Physical: ${w * dpr} x ${h * dpr}`);

個別要素のサイズ

const el = document.getElementById("myDiv");

// 要素のサイズ
el.offsetWidth;    // 幅 (border 含む)
el.offsetHeight;
el.clientWidth;    // 幅 (border 除く、padding 含む)
el.clientHeight;
el.scrollWidth;    // スクロールも含む全幅
el.scrollHeight;

// getBoundingClientRect (もっとも正確)
const rect = el.getBoundingClientRect();
console.log({
    width: rect.width,
    height: rect.height,
    top: rect.top,        // ビューポート上端からの距離
    left: rect.left,
    right: rect.right,
    bottom: rect.bottom
});

// 旧式 (jQuery)
$(el).width()         // padding 含まない
$(el).innerWidth()    // padding 含む
$(el).outerWidth()    // border 含む
$(el).outerWidth(true) // margin 含む

リサイズイベント

// ウィンドウサイズ変更を検知
window.addEventListener("resize", () => {
    console.log(`Resized to ${window.innerWidth} x ${window.innerHeight}`);
});

// パフォーマンス対策: debounce
let resizeTimer;
window.addEventListener("resize", () => {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(() => {
        // 重い処理は 200ms 後に
        recalculateLayout();
    }, 200);
});

// ResizeObserver (個別要素の監視、推奨)
const observer = new ResizeObserver(entries => {
    for (const entry of entries) {
        console.log("Size:", entry.contentRect.width, entry.contentRect.height);
    }
});
observer.observe(document.getElementById("myDiv"));

レスポンシブ判定

// ブレイクポイント判定
function getBreakpoint() {
    const w = window.innerWidth;
    if (w < 576) return "xs";
    if (w < 768) return "sm";
    if (w < 992) return "md";
    if (w < 1200) return "lg";
    return "xl";
}

// メディアクエリ
if (window.matchMedia("(max-width: 768px)").matches) {
    console.log("モバイル");
}

// イベントリスナー付き
const mq = window.matchMedia("(max-width: 768px)");
mq.addEventListener("change", e => {
    console.log(e.matches ? "モバイル" : "PC");
});

// 縦横判定
if (window.matchMedia("(orientation: portrait)").matches) { ... }

SP / PC 判定

// ユーザーエージェント (確実性低、推奨されない)
const isMobile = /Mobi|Android/i.test(navigator.userAgent);
const isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);

// 画面サイズで判定 (推奨)
const isMobile = window.innerWidth < 768;

// タッチデバイスか
const isTouch = "ontouchstart" in window;
const isTouch = navigator.maxTouchPoints > 0;

// より厳密な判定 (modern)
const isPointerCoarse = window.matchMedia("(pointer: coarse)").matches;
// → タッチ・スタイラスデバイス

iOS / Safari 特有の注意

// iOS Safari の innerHeight は URL バー表示状態で変わる
// → 100vh が想定より大きくなる現象

// 対策 1: CSS custom property + JS で計算
function setVh() {
    const vh = window.innerHeight * 0.01;
    document.documentElement.style.setProperty("--vh", `${vh}px`);
}
setVh();
window.addEventListener("resize", setVh);

/* CSS */
.full-height {
    height: 100vh;                    /* fallback */
    height: calc(var(--vh, 1vh) * 100);
}

// 対策 2: dvh / svh / lvh (modern、CSS のみ)
.full-height {
    height: 100dvh;  /* dynamic viewport height */
}

スクロール位置

// スクロール位置
window.scrollY;            // 縦
window.scrollX;            // 横
window.pageYOffset;        // 旧
document.documentElement.scrollTop;  // 旧

// スクロール
window.scrollTo(0, 100);
window.scrollTo({ top: 100, behavior: "smooth" });

// 要素までスクロール
element.scrollIntoView({ behavior: "smooth", block: "center" });

// ページ末尾までスクロール
window.scrollTo(0, document.documentElement.scrollHeight);

ビューポートメタタグ (HTML)











.padded {
    padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);
}

関連記事

編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. インストール(ファイルのダウンロード)
  2. npmを使用したプロジェクトの作成(mac)
  3. for 繰り返し処理
  4. ifの条件分岐とtemplateを用いたグループ化
  5. on:click クリック時のイベント処理
  6. modelとdata フォーム入力値とDOMへの即時反映
  7. computed(算出プロパティ)と使い方とdataとの違い
  8. ライフサイクルフック(created / mounted / updated / destroyedの使い方)
  9. $nextTickの使い方(ライフサイクルフック)
  10. メソッドの定義方法
  11. エラー一覧
  12. ルーティング設定
  13. aリンクの貼り方と動的URLの作成
  14. Mixinを利用した共通処理の記述方法
  15. v-bindによるデータ連携
  16. ヘッダー/フッターの共通コンポーネント
  17. ナビゲーションの現在ページをハイライトする方法
  18. 画面サイズの取得方法