【jQuery】レスポンシブデザインに使える条件分岐

結論のコード

$(function(){

  // 以下は変数です。画面の幅をwindowWidthに、
  var windowWidth = $(window).width(),

      // 1200をwindowLaptopに、
      windowLaptop = 1200,

      // 500をwindowMobileに入れてください。
      windowMobile = 500;

  // circleというクラスを持った要素をクリックしたら
  $('.circle').click(function(){

    // このクラスを持った要素の背景色をカラーコード#000080にしてください。
    $(this).css('background-color','#000080');

    // もし、画面の幅が1200より小さければ
    if (windowWidth < windowLaptop) {

      // このクラスを持った要素の背景色をカラーコード#ff7f50にしてください。
      $(this).css('background-color','#ff7f50');

    }
    // もし、、画面の幅が500より小さければ
    if (windowWidth < windowMobile) { 

      // このクラスを持った要素の背景色をカラーコード#006400にしてください。
      $(this).css('background-color','#006400');

    } 
  });
});

サンプル

http://xs437226.xsrv.jp/sample/responsive-jquery-conditional-branch/

灰色の円をクリックした時、

  • パソコンの場合は、青色
  • ラップトップの場合は、橙色

に変化します。

灰色の円のHTML

<body>
  <div class="circle"></div>
</body>

SCSS

body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  .circle {
    background-color: rgba(0,0,0,.5);
    height: 300px;
    width: 300px;
    border-radius: 50%;
    cursor: pointer;
  }
}

解説

この灰色の円を、クリックした時に色が変わるようにしたい時
f:id:khirok:20200422195441p:plain

jQueryでこのように書くことが出来ます。

$('.circle').click(function(){
    $(this).css('background-color','#000080'); 
});

クリック後

f:id:khirok:20200422200731p:plain

iPad Proなどのラップトップからクリックしたときは、橙色にしたい時

まず、画面の幅を変数に

var windowWidth = $(window).width(),

つぎに、ブレイクポイントを変数に代入しましょう。

  windowLaptop = 1200;

最後に、クリックイベント内でif文を書きます。

$('.circle').click(function(){
    if (windowWidth < windowLaptop) {
      $(this).css('background-color','#ff7f50');
    }
 }

クリック後

f:id:khirok:20200422203542p:plain

iPhone7などのスマホからクリックしたときは、緑色にしたい時

スマホ用のブレイクポイントを設定しましょう。

 windowMobile = 500;

if文は、こちらです。

if (windowWidth < windowMobile) { 
   $(this).css('background-color','#006400');
 }

クリック後

f:id:khirok:20200422203839p:plain