スマートフォンからのアクセス時にのみ、Javasciptを適用する方法を先日も書きましたが、この方法よりも、もっとスマートなブラウザAPIを利用する方法がありましたので、ご紹介します。
window.matchMedia
MediaQueryListという、クエリの結果を返すオブジェクトを利用します。引用元:Responsive Javascript
javascript
//Prepare a MediaQueryList var mql = window.matchMedia("(max-width:768px)"); //Add a listener to the MediaQueryList mql.addListener(function(e){ if(e.matches){ console.log('enter mobile'); } });
MediaQueryList オブジェクトを使ってデバイスの向きを検知
ちなみに、同じオブジェクトを使って、デバイスの向きも検知できます。
引用元:スクリプトからのメディアクエリの使用
javascript
var mql = window.matchMedia("(orientation: portrait)"); mql.addListener(handleOrientationChange); handleOrientationChange(mql); function handleOrientationChange(mql) { if (mql.matches) { /* The device is currently in portrait orientation */ } else { /* The device is currently in landscape orientation */ } }
デバイス向きの検知は一度実行して、その時点で初期化するのが良いようです。
(上記例でいうhandleOrientationChangeの実行)
で、必要なくなったらremoveListenerで通知を終了します。
javascript
//通知の終了 mql.removeListener(handleOrientationChange);
ブラウザサポート
- IE10以上
- Chrome9以上
- Firefox6以上
- Safari5.1以上
- Opera17以上
IEはやっぱり対応Versionが限られるので、それだけ注意ですね。
コメントを残す