繁体   English   中英

用于检测移动浏览器屏幕宽度的Javascript?

[英]Javascript to detect mobile browser screen width?

我使用screen.width来获取浏览器的宽度。 它与iphone safari工作正常,但在Android手机中没有工作(它显示800宽度的Android浏览器)。

是否有任何兼容的方式来获得屏幕宽度。 我不想使用UserAgent来检查它的移动浏览器。 我想使用javascript,逻辑应该包括屏幕宽度。

知道问题 - 见这里

当页面首次加载screen.widthscreen.height是错误的。 尝试像这样的超时:

setTimeout(CheckResolution, 300);

CheckResolution是你的职能。

您可以尝试使用此URL来检测屏幕大小并应用CSS样式

要么

<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

对于那些有兴趣获取浏览器宽度值的人,我测试了几个选项:

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

window.innerWidth 

以下是1200px窗口的结果:

$( 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

我发现使用window.outerWidth给出了正确的值。 使用BrowserStack android模拟器测试了这一点。

只需阅读这两个网址即可。 它应该可以帮助您获得所需。

http://www.quirksmode.org/blog/archives/2010/08/combining_media.html http://www.quirksmode.org/mobile/tableViewport.html

仅供参考,Android可能是800px宽。 请参阅此文章: 了解Samsung Galaxy Tab屏幕密度

编辑:哦,我认为另一个人比我指出了Android错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM