2
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?

【JavaScript】画面の幅によって処理を分ける方法

Posted at

画面の幅を検証する方法

画面の幅が一定の値か検証するにはwindow.matchMedia()を使用します。

// ウィンドウサイズが640px以下ならtrue
matchMedia('(min-width:640px)').matches

// ウィンドウサイズが768px以上1024px以下ならtrue
matchMedia('(min-width:768px) and (max-width:1024px)').matches

画面幅が変更された際に処理を分ける

画面幅が変更された際に画面の幅を検証し、処理を分けるには以下のようにします。

const mediaQueryList = matchMedia('(min-width:640px)')

mediaQueryList.addEventListener('change', (ev) => {
    if (ev.matches) {
        console.log('画面幅:640px以上')
    } else {
        console.log('画面幅:640px未満')
    }
})

参考

2
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
2
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?