JavaScript如何检测移动浏览器屏幕宽度?

13

我使用了screen.width来获取浏览器的宽度。在iPhone Safari上运行良好,但在Android手机上无法正常工作(对于Android浏览器它显示800宽度)。

有没有一种兼容的方法可以获取屏幕宽度?我不想使用UserAgent来检查是否为移动浏览器。我想使用JavaScript,并且逻辑应包括屏幕宽度。

5个回答

4
这是一个已知的问题 - 可以在这里查看。
当页面第一次加载时,screen.widthscreen.height的值是错误的。可以尝试使用类似以下的延时操作:
setTimeout(CheckResolution, 300);

其中CheckResolution是您的函数。


3
你可以尝试使用这个链接来检测屏幕大小并应用CSS样式:http://www.ilovecolors.com.ar/detect-screen-size-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

1

如果您想获取浏览器的宽度值,我测试了几个选项:

我正在使用bootstrap 3,唯一与IE和Chrome匹配bootstrap 3断点的解决方案是:

window.innerWidth 

这里是使用1200像素窗口的结果:
Chrome
$( 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 

互联网浏览器 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

0

0

我发现使用window.outerWidth可以得到正确的值。我在BrowserStack的Android模拟器上测试过。


这只会返回整个窗口的宽度,包括 Chrome 和其他所有内容。 - malthoff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接