0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

メディアクエリを使ってJavaScriptの処理を分岐させる

Last updated at Posted at 2023-08-07

メディアクエリを使った処理

(function() {

  // メディアクエリの定義
  const mediaQuery = window.matchMedia('(max-width: 768px)');

  function handleScreenChange(e) {
    // デバイス別のclassを付与したい要素(例:.header)
    const header = document.querySelector('.header');

    if (e.matches) {
      // 768px以下の場合(SP)
      header.classList.add('is_sp');
      header.classList.remove('is_pc');

    } else {
      // 768pxより大きい場合(PC)
      header.classList.add('is_pc');
      header.classList.remove('is_sp');

    }
  }

  // メディアクエリの状態が変更されたときにhandleScreenChange関数が呼ばれるようにする
  mediaQuery.addEventListener('change', handleScreenChange);

  // 初期ロード時にも状態をチェック
  handleScreenChange(mediaQuery);

})();
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?