2016-04-15 35 views
5

我見過很多方法來檢測設備的屏幕方向,包括使用檢查來測試innerWidth與innerHeight,就​​像這樣。如何使用JavaScript檢測設備方向?

function getOrientation(){ 
    var orientation = window.innerWidth > window.innerHeight ? "Landscape" : "Primary"; 
    return orientation; 
} 

但如果我要檢查什麼屏幕方向使用事件偵聽器改變呢?我試過這段代碼,但它對我不起作用。

function doOnOrientationChange() 
    { 
    switch(window.orientation) 
    { 
     case -90: 
     case 90: 
     alert('landscape'); 
     break; 
     default: 
     alert('portrait'); 
     break; 
    } 
    } 

    window.addEventListener('orientationchange', doOnOrientationChange); 

    // Initial execution if needed 
    doOnOrientationChange(); 

它不檢測設備方向,並且偵聽器沒有爲我註冊(我正在使用Chrome的設備模擬器)。

回答

12

兩種方法可以做到這一點:

首先,作爲每Screen API文檔,使用> =鉻38,Firefox和IE 11,屏幕對象是可用於不僅查看方向,而且還註冊每次設備方向發生變化時,監聽器都會響應。

screen.orientation.type將明確地讓你知道的取向是什麼,併爲聽衆可以用喜歡的東西很簡單:

screen.orientation.onchange = function(){ 
    // logs 'portrait' or 'landscape' 
    console.log(screen.orientation.type.match(/\w+/)[0]); 
}; 

其次,與其他瀏覽器如Safari不與屏幕兼容的相容性, this post顯示您可以在窗口大小調整時繼續使用innerWidth和innerHeight。

function getOrientation(){ 
    var orientation = window.innerWidth > window.innerHeight ? "Landscape" : "Portrait"; 
    return orientation; 
} 

window.onresize = function(){ getOrientation(); } 
+0

值得注意的是,該解決方案僅適用於智能手機上的Chrome瀏覽器> = 39和Firefox Mobile。 OP添加了標籤「ios」,Screen API不是解決方案。 – Popatop15