// Detect whether device supports orientationchange event, otherwise fall back to the resize event.
var supportsOrientationChange = "onorientationchange" in window,
orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

window.addEventListener(orientationEvent, function() {
alert('HOLY ROTATING SCREENS BATMAN:' + window.orientation + " " + screen.width);
}, false);

(function(){
var supportsOrientation = (typeof window.orientation == 'number' && typeof window.onorientationchange == 'object');
var HTMLNode = document.body.parentNode;
var updateOrientation = function() {
// rewrite the function depending on what's supported
if(supportsOrientation) {
updateOrientation = function() {
var orientation = window.orientation;</code>

switch(orientation) {
case 90: case -90:
orientation = 'landscape';
break;
default:
orientation = 'portrait';
}

// set the class on the HTML element (i.e. )
HTMLNode.setAttribute('class', orientation);
}
} else {
updateOrientation = function() {
// landscape when width is biggest, otherwise portrait
var orientation = (window.innerWidth > window.innerHeight) ? 'landscape': 'portrait';

// set the class on the HTML element (i.e. )
HTMLNode.setAttribute('class', orientation);
}
}

updateOrientation();
}
var init = function() {
// initialize the orientation
updateOrientation();

if(supportsOrientation) {
window.addEventListener('orientationchange', updateOrientation, false);
} else {
// fallback: update every 5 seconds
setInterval(updateOrientation, 5000);
}

}
window.addEventListener('DOMContentLoaded', init, false);
})();
(function(){var e=typeof window.orientation=="number"&&typeof window.onorientationchange=="object",f=document.body.parentNode;function c(){c=e?function(){var d=window.orientation;switch(d){case 90:case -90:d="landscape";break;default:d="portrait"}f.setAttribute("class",d)}:function(){f.setAttribute("class",window.innerWidth>window.innerHeight?"landscape":"portrait")};c()}window.addEventListener("DOMContentLoaded",function(){c();e?window.addEventListener("orientationchange",c,false):setInterval(c,5E3)},false)})();

摘自: http://davidbcalhoun.com/2010/dealing-with-device-orientation

相关文章