LoginSignup
7
7

More than 5 years have passed since last update.

JavascriptでWebサイトのレスポンシブ対応

Last updated at Posted at 2016-09-06

内容

  • ウィンドウサイズに応じて <body> タグにクラスを追記する
  • 読み込み時とリサイズ時に処理を実行
test.html
<meta name="viewport" content="width=device-width, initial-scale=1">
↑ headerに入れる

<script type="text/javascript">
    $(window).on('load resize', function(){
        var x = $(window).width();
        if (x <= 906) {
            $(document.body).addClass('narrow');
            if (x <= 767) {
                $(document.body).addClass('for-tablet');
                if (x <= 479) {
                    $(document.body).addClass('for-mobile');
                } else {
                    $(document.body).removeClass('for-mobile');
                }
            } else {
                $(document.body).removeClass('for-tablet');
                $(document.body).removeClass('for-mobile');
            }
        } else {
            $(document.body).removeClass('narrow');
            $(document.body).removeClass('for-tablet');
            $(document.body).removeClass('for-mobile');
        }
    });
</script>

あとは適当にCSSへ定義していく

style.css
.hoge{
}
#タブレットスマートフォン向け幅767px以下の場合
.hoge .for-tablet {
}
#スマートフォン向け幅479px以下の場合
.hoge .for-mobile {
}

cssのメディアクエリ? そんなものはなかった

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