<!Doctype html>
<html>
<head>
<meta charset="utf-8">
<meta id="viewport" name="viewport" content="width=device-width,initial-scale=1.0;">
<title>橫豎屏切換檢測</title>
<style type="text/css">
.landscape body {
background-color: #ff0000;
}.portrait body {
background-color: #00ffff;
}
</style>
<script type="text/javascript">
// window.orientation :這個屬性給出了當前設備的屏幕方向,0表示豎屏,正負90表示橫屏(向左與向右)模式
// onorientationchange : 在每次屏幕方向在橫豎屏間切換后,就會觸發這個window事件,用法與傳統的事件類似
(function(){
var supportOrientation=(typeof window.orientation == "number" && typeof window.onorientationchange == "object"); //判斷瀏覽器是否支持orientationvar updateOrientation=function(){
if(supportOrientation){
updateOrientation=function(){
var orientation=window.orientation;
switch(orientation){
case 90:
case -90:
orientation="landscape"; //橫屏
break;
default:
orientation="portrait"; //豎屏
}
document.body.parentNode.setAttribute("class",orientation);
};
}else{
updateOrientation=function(){ //如果當前瀏覽器不支持orientation,則使用最簡單的方法(判斷窗口的高寬)
var orientation=(window.innerWidth > window.innerHeight)? "landscape":"portrait";
document.body.parentNode.setAttribute("class",orientation);
};
}
updateOrientation();
};var init=function(){
updateOrientation();
if(supportOrientation){
window.addEventListener("orientationchange",updateOrientation,false);
}else{
window.setInterval(updateOrientation,5000);
}
};
window.addEventListener("DOMContentLoaded",init,false);
})();
</script>
</head>
<body>
<div>
移動端Web開發如何處理橫豎屏
</div>
</body>
</html>