レスポンシブデザインに役立つ!JavaScriptでブラウザのビューポートの寸法を取得する

2024-04-12

JavaScriptでブラウザのビューポートの寸法を取得する方法

window.innerWidth と window.innerHeight を使う

最も簡単な方法は、window.innerWidthwindow.innerHeight プロパティを使うことです。これらのプロパティは、それぞれブラウザの幅と高さをピクセル単位で返します。

const width = window.innerWidth;
const height = window.innerHeight;

console.log(`幅: ${width}px, 高さ: ${height}px`);

document.documentElement.clientWidth と document.documentElement.clientHeight を使う

window.innerWidthwindow.innerHeight は、スクロールバーを含めたビューポートの寸法を返します。スクロールバーを除いた寸法を取得したい場合は、document.documentElement.clientWidthdocument.documentElement.clientHeight プロパティを使うことができます。

const width = document.documentElement.clientWidth;
const height = document.documentElement.clientHeight;

console.log(`幅: ${width}px, 高さ: ${height}px`);

getComputedStyle を使って、ビューポートのスタイルを取得することもできます。

const width = getComputedStyle(document.documentElement).getPropertyValue('width');
const height = getComputedStyle(document.documentElement).getPropertyValue('height');

console.log(`幅: ${width}, 高さ: ${height}`);

addEventListener を使う

ブラウザのサイズが変更されたときに、イベントリスナーを使ってビューポートの寸法を取得することができます。

window.addEventListener('resize', () => {
  const width = window.innerWidth;
  const height = window.innerHeight;

  console.log(`幅: ${width}px, 高さ: ${height}px`);
});

クロスブラウザ対応

上記の方法は、ほとんどのブラウザで動作します。ただし、古いブラウザでは一部の機能がサポートされていない場合があります。クロスブラウザ対応するには、以下の点に注意する必要があります。

  • window.innerWidthwindow.innerHeight は、IE8 以前ではサポートされていません。
  • document.documentElement.clientWidthdocument.documentElement.clientHeight は、IE9 以前ではサポートされていません。
  • getComputedStyle は、IE8 以前ではサポートされていません。

古いブラウザにも対応したい場合は、以下のコードのように、複数の方法を組み合わせて使うことができます。

let width, height;

if (window.innerWidth && window.innerHeight) {
  width = window.innerWidth;
  height = window.innerHeight;
} else if (document.documentElement.clientWidth && document.documentElement.clientHeight) {
  width = document.documentElement.clientWidth;
  height = document.documentElement.clientHeight;
} else {
  const style = getComputedStyle(document.documentElement);
  width = style.getPropertyValue('width');
  height = style.getPropertyValue('height');
}

console.log(`幅: ${width}px, 高さ: ${height}px`);

JavaScriptでブラウザのビューポートの寸法を取得するには、いくつかの方法があります。どの方法を使うかは、ブラウザの互換性や用途によって異なります。




<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ブラウザのビューポートの寸法を取得</title>
</head>
<body>
  <script>
    // window.innerWidth と window.innerHeight を使う
    const width1 = window.innerWidth;
    const height1 = window.innerHeight;

    // document.documentElement.clientWidth と document.documentElement.clientHeight を使う
    const width2 = document.documentElement.clientWidth;
    const height2 = document.documentElement.clientHeight;

    // getComputedStyle を使う
    const width3 = getComputedStyle(document.documentElement).getPropertyValue('width');
    const height3 = getComputedStyle(document.documentElement).getPropertyValue('height');

    console.log(`
      window.innerWidth: ${width1}px, window.innerHeight: ${height1}px
      document.documentElement.clientWidth: ${width2}px, document.documentElement.clientHeight: ${height2}px
      getComputedStyle: ${width3}, ${height3}
    `);
  </script>
</body>
</html>
window.innerWidth: 1280px, window.innerHeight: 720px
document.documentElement.clientWidth: 1280px, document.documentElement.clientHeight: 720px
getComputedStyle: 1280px, 720px
  • ビューポートの寸法は、ユーザーがブラウザのウィンドウをリサイズしたり、デバイスの向きを変えたりすると変更されます。



ビューポートの寸法を取得するその他の方法

document.body.clientWidthdocument.body.clientHeight プロパティは、HTML <body> 要素の幅と高さをピクセル単位で返します。ただし、この方法は、IE8 以前ではサポートされていません。

const width = document.body.clientWidth;
const height = document.body.clientHeight;

console.log(`幅: ${width}px, 高さ: ${height}px`);

document.querySelector メソッドを使って、特定の要素の寸法を取得することができます。例えば、以下のようにして、ブラウザのウィンドウの寸法を取得することができます。

const width = document.querySelector('body').clientWidth;
const height = document.querySelector('body').clientHeight;

console.log(`幅: ${width}px, 高さ: ${height}px`);

getBoundingClientRect メソッドを使って、要素の矩形領域を取得することができます。この矩形領域には、要素の幅と高さも含まれます。

const element = document.querySelector('body');
const rect = element.getBoundingClientRect();

const width = rect.width;
const height = rect.height;

console.log(`幅: ${width}px, 高さ: ${height}px`);

ライブラリを使う

jQueryなどのJavaScriptライブラリを使うと、ビューポートの寸法を取得するコードを簡単に書くことができます。

// jQueryを使う場合
const width = $(window).width();
const height = $(window).height();

console.log(`幅: ${width}px, 高さ: ${height}px`);

javascript cross-browser viewport


もうコピペで手間取らない!HTMLテキスト入力欄をワンクリックで全選択

最もシンプルで汎用性の高い方法です。このコードは、getElementById() メソッドを使ってテキスト入力欄を取得し、click イベントリスナーを追加します。イベントリスナー内で、select() メソッドを呼び出すことで、入力欄内の全てのテキストを選択します。...


JavaScript、Angular、RxJSの達人になるための秘訣!flatMap、mergeMap、switchMap、concatMapを使いこなそう!

flatMap(別名:mergeMap)1つの入力Observableを複数のObservableに分割し、それらを平坦化して1つの出力Observableに統合します。複数のObservableを同時に処理し、出力される順番は非同期処理の完了順になります。...


【保存版】mat-form-fieldの高さをCSS、コンポーネントプロパティ、ngStyleで変更する方法を徹底解説

CSS を使って、mat-form-field コンポーネントのスタイルを直接変更する方法です。これが最も一般的で柔軟性の高い方法です。以下の CSS コード例は、mat-form-field の高さを 48px に設定します。特定の mat-form-field コンポーネントのみを対象にしたい場合は、CSS セレクタをより具体的にする必要があります。例えば、ID を使って特定のコンポーネントを対象にするには、以下のようになります。...


React Testing Library で debug 出力の一部が見えない問題を解決するその他の方法

react-testing-library を使用してテストを実行しているときに、debug 出力のすべてが表示されないことがあります。これは、テスト環境とデベロプメント環境の違いによって発生する可能性があります。原因この問題にはいくつかの原因が考えられます。...


SQL SQL SQL SQL Amazon で見る



JavaScript、HTML、jQuery で画面サイズ、現在のウェブページ、ブラウザウィンドウのサイズを取得する方法

ここでは、JavaScript、HTML、jQuery を使ってこれらのサイズを取得する方法を解説します。画面サイズは、window. screen オブジェクトを使って取得することができます。このコードは、window. screen. width と window