QED

私はこの世界について驚くべき真理を発見した。だが、それを記すにはこのブログは狭すぎる。

ウィンドウのリサイズ時にイベントを実行する(jQuery使用)

ウィンドウのリサイズ時にresizeEvent()を実行する。

// (スマホ用)画面の向き

var ORIENTATION_LANDSCAPE = 1;
var ORIENTATION_PORTRAIT  = 2;

var orientation = Math.abs(window.orientation) === 90
      ? ORIENTATION_LANDSCAPE : ORIENTATION_PORTRAIT;

if ("onorientationchange" in window) {
	// スマホ・タブレットの場合は、向きが変わった時に
	var _orientation_event;
	  if ( navigator.userAgent.indexOf('iPhone') > 0
	    || navigator.userAgent.indexOf('iPad') > 0
	    || navigator.userAgent.indexOf('iPod') > 0) {
		// iOSの場合は onorientationchange イベントを使う
		_orientation_event = 'orientationchange';
	  } else {
		// Androidの場合は resize イベントを使う
		_orientation_event = 'resize';
	  }
	$(window).bind(_orientation_event,function(){
	    if (Math.abs(window.orientation) === 90) {
		if (orientation!==ORIENTATION_LANDSCAPE){
		    // 縦→横になった
		    orientation = ORIENTATION_LANDSCAPE;
		    resizeEvent();
		}
	    }else{
		if (orientation!==ORIENTATION_PORTRAIT){
		    // 横→縦になった
		    orientation = ORIENTATION_PORTRAIT;
		    resizeEvent();
		}
	    }
	});
} else {
	// PCの場合はウィンドウのリサイズ時に
	$(window).resize(function(){
	  resizeEvent();
	});
}

イベントをbindするためにだけjQueryを利用しているので、その部分を

if (window.addEventListener) {
    window.addEventListener(_orientation_event, resizeEvent, false);
  } else if (window.attachEvent) {
    window.attachEvent(_orientation_event, resizeEvent);
  } else {
    window[_orientation_event] = resizeEvent;
  }

とかに置き換えればjQueryなしでも動きます。

 

ちなみにiOSAndroidで使用しているイベントが違うのは、このブログを参照

iPhoneAndroid の onOrientationChange タイミングの違い

http://d.hatena.ne.jp/makog/20110811/1313079509