DIV CSS 佈局教程網

移動端橫屏偵測的 JavaScript 實作(beta)
編輯:關於JavaScript     

行動裝置旋轉螢幕時,網頁需要跟著調整佈局。以下是判斷橫向與直向的核心程式碼:

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<script src="https://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script>
var orientation = 0;
function screenOrientationEvent(){
    if(orientation == 0) {
        document.getElementById("change").value = "豎";
        $("body").css({
            'transform':'rotate(90deg)',
            '-webkit-transform':'rotate(90deg)',
            '-moz-transform':'rotate(90deg)'
        });
    } else {
        document.getElementById("change").value = "橫";
        $("body").css({
            'transform':'rotate(0deg)',
            '-webkit-transform':'rotate(0deg)',
            '-moz-transform':'rotate(0deg)'
        });
    }
}

var innerWidthTmp = window.innerWidth;

//橫豎屏事件監聽方法
function screenOrientationListener(){
    try{
        var iw = window.innerWidth; //屏幕方向改變處理
        if(iw != innerWidthTmp){
            if(iw > window.innerHeight) {
                orientation = 90;
            } else {
                orientation = 0;
            }
            //調用轉屏事件
            screenOrientationEvent();
            innerWidthTmp = iw;
        }
    } catch(e){ alert(e); };
    //間隔固定事件檢查是否轉屏,默認500毫秒
    setTimeout("screenOrientationListener()", 500);
}

//啟動橫豎屏事件監聽
screenOrientationListener();
</script>
<body onload="screenOrientationEvent()">
<input id="change" type="text" value=""/>
</body>
</html>

這段程式碼被判為 beta,是因為它有幾個明顯可改進之處。

判斷方式是輪詢:每 500 毫秒比對一次 innerWidth 是否變化,再拿寬高關係推斷方向。輪詢有延遲,也在手機空耗電力。

以 setTimeout("字串", 500) 傳字串而非函式,相當於一次 eval,效能與可讀性都不好。

用 rotate(90deg) 旋轉整個 body 並非常態做法——它會讓畫面外的內容溢出、捲軸行為異常,通常只在特定情境(例如強制橫向的遊戲或影片頁)才會這樣處理。

現代做法有兩個更好的選擇。其一,直接監聽 orientationchange 或 resize 事件,不必輪詢:

function handleOrientation(){
    var isPortrait = window.innerWidth < window.innerHeight;
    console.log(isPortrait ? '直向' : '橫向');
}

// 監聽方向變化
window.addEventListener('orientationchange', handleOrientation);
// 部分舊版 Android 瀏覽器只觸發 resize,可一併監聽
window.addEventListener('resize', handleOrientation);
// 頁面載入時先執行一次
handleOrientation();

其二,若只是要調整版面,用 CSS 媒體查詢會比 JavaScript 乾淨得多:

/* 直向 */
@media screen and (orientation: portrait) {
    .container { width: 100%; }
}
/* 橫向 */
@media screen and (orientation: landscape) {
    .container { max-width: 900px; margin: 0 auto; }
}

媒體查詢由瀏覽器在樣式計算階段處理,不佔用主執行緒,也不需要旋轉 body。只有在必須依方向執行邏輯(例如切換影片播放器模式、重繪 canvas 尺寸)時,才真的需要 JavaScript 介入——而這時也該用事件監聽取代輪詢。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved