2011-12-14 129 views
13

我用screen.width來獲得瀏覽器的寬度。它與iPhone safari很好地工作,但沒有在Android手機(它顯示800寬度爲Android瀏覽器)工作。使用Javascript來檢測手機瀏覽器的屏幕寬度?

是否有任何兼容的方式來獲得屏幕寬度。我不想用UserAgent來檢查它的移動瀏覽器。想要使用一個JavaScript的,邏輯應該包括屏幕寬度。

回答

3

你可以試試這個網址爲detect screen size and apply a CSS style

<script type="text/javascript"> 

    function getWidth() 
    { 
    xWidth = null; 
    if(window.screen != null) 
     xWidth = window.screen.availWidth; 

    if(window.innerWidth != null) 
     xWidth = window.innerWidth; 

    if(document.body != null) 
     xWidth = document.body.clientWidth; 

    return xWidth; 
    } 
function getHeight() { 
    xHeight = null; 
    if(window.screen != null) 
    xHeight = window.screen.availHeight; 

    if(window.innerHeight != null) 
    xHeight = window.innerHeight; 

    if(document.body != null) 
    xHeight = document.body.clientHeight; 

    return xHeight; 
} 

</script> 


screen.height   shows the height of the screen 
screen.width   shows the width of the screen 
screen.availHeight shows height but removes the interface height like taskbar, and browser menu etc. 
screen.availWidth same as above,instead gives available width 
4

它知道問題 - 看here

當第一次加載頁面的screen.widthscreen.height是錯誤的。 嘗試超時這樣的:

setTimeout(CheckResolution, 300); 

哪裏CheckResolution是你的函數。

0

我發現使用window.outerWidth給出了正確的值。使用BrowserStack android模擬器對此進行了測試。

+0

這只是返回包括鉻和一切整個窗口的寬度。 – malthoff 2013-09-27 08:48:51

1

對於那些有興趣獲得瀏覽器的寬度值,我測試幾個選項:

我使用自舉3和唯一的解決方案相匹配的自舉用IE和鉻3個斷點中:

window.innerWidth 

下面是結果與1200像素窗口:

$(window).width(): 1183 
$(document).width():1183 
screen.width: 1536 
$(window).innerWidth():1183 
$(document).innerWidth():1183 
window.innerWidth: 1200 
$(document).outerWidth():1183 
window.outerWidth: 1216 
document.documentElement.clientWidth: 1183 

的Internet Explorer 10

$(window).width(): 1200 
$(document).width():1200 
screen.width: 1536 
$(window).innerWidth():1200 
$(document).innerWidth():1200 
window.innerWidth: 1200 
$(document).outerWidth():1200 
window.outerWidth: 1214 
document.documentElement.clientWidth: 1200 
相關問題