我试图写一个JavaScript函数,以获得当前的浏览器宽度。

我找到了这个:

console.log (document.body.offsetWidth);

但问题是,如果主体宽度为100%,它就会失败。

还有其他更好的功能或解决方案吗?


当前回答

这很麻烦。我建议跳过这些废话,使用jQuery,它让你只需要执行$(window).width()。

其他回答

var w = window.innerWidth;
var h = window.innerHeight;
var ow = window.outerWidth; //including toolbars and status bar etc.
var oh = window.outerHeight;

两者都返回整数并且不需要jQuery。跨浏览器兼容的。

我经常发现jQuery返回width()和height()的无效值。

这是特拉维斯回答的重要补充;你需要把getWidth()放在你的文档主体中,以确保滚动条宽度被计算在内,否则浏览器的滚动条宽度会从getWidth()中减去。我做了什么;

<body>
<script>
function getWidth(){
return Math.max(document.body.scrollWidth,
document.documentElement.scrollWidth,
document.body.offsetWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth);
}
var aWidth=getWidth();
</script>
</body>

然后在任意位置调用width变量。

function getWidth() { return Math.max( document.body.scrollWidth, document.documentElement.scrollWidth, document.body.offsetWidth, document.documentElement.offsetWidth, document.documentElement.clientWidth ); } function getHeight() { return Math.max( document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight, document.documentElement.clientHeight ); } console.log('Width: ' + getWidth() ); console.log('Height: ' + getHeight() );

这很麻烦。我建议跳过这些废话,使用jQuery,它让你只需要执行$(window).width()。

一个适应的解决方案,现代JS的特拉维斯的答案:

const getPageWidth = () => {
  const bodyMax = document.body
    ? Math.max(document.body.scrollWidth, document.body.offsetWidth)
    : 0;

  const docElementMax = document.documentElement
    ? Math.max(
        document.documentElement.scrollWidth,
        document.documentElement.offsetWidth,
        document.documentElement.clientWidth
      )
    : 0;

  return Math.max(bodyMax, docElementMax);
};