技術

javascriptで画面サイズ毎に処理をしたい時

投稿日:

こんにちは

今回はjavascriptで画面サイズ毎に処理をしたい時にオススメの方法を紹介します。

メディアクエリを設定するときって

@media screen and (max-width: 767px) { 
  /* スマホ */
}
@media screen and (min-width: 768px) and ( max-width: 1024px) {
  /* タブレット */
}
@media screen and (min-width:1025px) {
  /* PC */
}

みたいな感じになるかと思います。

そしてjavascriptでスマホの画面サイズ時だけ処理をしたいというときに

$width = window.width()
if ($width < 768) {
  // やりたい処理
}

まずブラウザの横幅を取得してメディアクエリで設定した値と比較します。
ただ、このやり方だと修正が入った時けっこうめんどくさいので
代わりにfont-familyを使います。

こんな感じで設定します。

@media screen and (max-width: 767px) { 
  /* スマホ */
  .l-sizedetect {
    font-family: 'sp';
  }
}
@media screen and (min-width: 768px) and ( max-width: 1024px) {
  /* タブレット */
  .l-sizedetect {
    font-family: 'tablet';
  }
}
@media screen and (min-width:1025px) {
  /* PC */
  .l-sizedetect {
    font-family: 'pc';
  }
}

後はjavascript側でl-sizedetectのcssを取得してやればOKです。

if ($('l-sizedetect').css('font-family') === 'sp') {
  // スマホでやりたい処理
} else if($('l-sizedetect').css('font-family') === 'tablet') {
  // タブレットでやりたい処理
}

-技術

執筆者:


comment

メールアドレスが公開されることはありません。 ※ が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください。

関連記事

[Xcode] SDK Version Issue – This app was built with the iOS 12.0 SDK. Starting March 2019, all iOS apps submitted to the App Store must be built with the iOS 12.1 SDK or later, included in Xcode 10.1 or later.

こんにちは。たなかです。 2019年、ブログ初更新になります。今年もよろしくお願 …

no image

【nginx/unicorn】(13: Permission denied) while connecting to upstream

どうも中田です。 AWS上でAPIサーバを構築してて、 * Webサーバ:ngi …

no image

ng-ifのelse句でコンポーネントのプロパティと名前重複

こんにちは、コーテッグのこやまです。 Angularを触っていたら、コンポーネン …

no image

【Vagrant】はじめまして!はじめました!

どうも中田です。 仮想マシンと言えば、VMWare、EC2、VirtualBox …

no image

HTMLエンティティを探すならHTML Arrowsがオススメ!

こんにちは htmlエンティティっていうのを聞いたことがありますか? アンパサン …