[JS]柔軟なclassの設定が可能なResponsive Web Design用の超軽量(1KB)スクリプト -syze
Post on:2012年1月16日
jQueryなどの他のスクリプトに依存せず、表示サイズに応じてスタイルシート用のclassを設定し、iPhone, iPad, デスクトップなどのクロスデバイス用のコンテンツを作成できる超軽量スクリプトを紹介します。

syze: Think @media queries powered by Javascript
[ad#ad-2]
syzeのデモ
デモはいくつか用意されていますが、最もベーシックなものを紹介します。

demo 1:幅1200pxで表示
タブレット用の画像(tablet-wide-256x256.png)を表示

demo 1:幅768pxで表示
スマートフォン用の画像(mobile-wide-128x128.png)を表示
[ad#ad-2]

demo 1:幅1920pxで表示
デスクトップ用の画像(hdsize-wide-512x512.png)を表示
syzeの使い方
上記のdemo 1を例に実装方法を紹介します。
外部ファイル
当スクリプトを外部ファイルとして指定します。
<script src="syze.min.js"></script>
JavaScript
demo1では表示サイズの数値を元に、class名にもその数値を利用します。
syze.sizes(320, 480, 768, 1024, 1920);
- class名
-
- .is320(0-479px)
- .is480(480-767px)
- .is768(768-1023px)
- .is1024(1024px-1079px)
- .is1920(1920+px)
CSS
設定が完了したら、あとはサイズごとにスタイルシートを設定します。
body { background: no-repeat center center; } .is320 body { background-image: url(mobile-tall-128x128.png); } .is480 body { background-image: url(mobile-wide-128x128.png); } .is768 body { background-image: url(tablet-tall-256x256.png); } .is1024 body { background-image: url(tablet-wide-256x256.png); } .is1920 body { background-image: url(hdsize-wide-512x512.png); }
class名は数値以外も可
class名の設定は「.is320」のような数値だけでなく、よりフレンドリーな名前を使うこともできます。

サイズを設定し、それに対応する名前を設定します。
syze.sizes(320, 480, 768, 1024, 1920).names({ 320:'MobileTall', 480:'MobileWide', 768:'TabletTall', 1024:'TabletWide', 1920:'HdSizeWide' });
- class名
-
- .MobileTall(0-479px)
- .MobileWide(480-767px)
- .TabletTall(768-1023px)
- .TabletWide(1024-1079px)
- .HdSizeWide(1920+px)
5つもいらない、もっとシンプルに、という人には、下記のような設定も可能です。
syze.sizes(480, 768, 1920).names({ 320:'Mobile', 768:'Tablet', 1920:'HdSize' });
- class名
-
- .Mobile(0-767px)
- .Tablet(768-1079px)
- .HdSize(1920+px)
sponsors