2011-12-14 127 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 
相关问题