【问题标题】:How to get browser width using JavaScript code?如何使用 JavaScript 代码获取浏览器宽度?
【发布时间】:2010-11-05 12:58:36
【问题描述】:

我正在尝试编写一个 JavaScript 函数来获取当前浏览器宽度。

我找到了这个:

console.log(document.body.offsetWidth);

但是如果body的宽度是100%就会失败。

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

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    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() );

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案2】:

    Travis 回答的重要补充;您需要将 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>
    

    然后在任何地方调用 aWidth 变量。

    【讨论】:

      【解决方案3】:

      Travis 回答的现代 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);
      };
      

      【讨论】:

        【解决方案4】:

        2017 年更新

        我最初的答案是在 2009 年写的。虽然它仍然有效,但我想在 2017 年更新它。浏览器的行为仍然可以不同。我相信 jQuery 团队在维护跨浏览器一致性方面做得很好。但是,没有必要包含整个库。在 jQuery 源代码中,相关部分位于 line 37 of dimensions.js。在这里它被提取并修改为独立工作:

        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() );

        原答案

        由于所有浏览器的行为不同,您需要先测试值,然后使用正确的值。这是一个为您执行此操作的函数:

        function getWidth() {
          if (self.innerWidth) {
            return self.innerWidth;
          }
        
          if (document.documentElement && document.documentElement.clientWidth) {
            return document.documentElement.clientWidth;
          }
        
          if (document.body) {
            return document.body.clientWidth;
          }
        }
        

        高度也类似:

        function getHeight() {
          if (self.innerHeight) {
            return self.innerHeight;
          }
        
          if (document.documentElement && document.documentElement.clientHeight) {
            return document.documentElement.clientHeight;
          }
        
          if (document.body) {
            return document.body.clientHeight;
          }
        }
        

        在您的脚本中使用getWidth()getHeight() 调用这两个函数。如果没有定义浏览器的原生属性,它将返回undefined

        【讨论】:

        • 最佳答案,因为我不必为基于浏览器窗口宽度的简单重定向包含 33k 库
        • 与 jQuery 的实现相比,这会产生始终如一的正确(或预期)结果。
        • ... 这三个中的每一个都显示了一些结果,并且所有结果(宽度)都不同。例如,对于 Google Chrome,请参阅 self.innerWidth 423document.documentElement.clientWidth 326document.body.clientWidth 406。在这种情况下,问题是:哪个是正确的,使用哪个?例如我想调整谷歌地图的大小。 326或423差别很大。如果宽度~700,那么看759、735、742(差别不大)
        • @user2118559 var pageWidth = Math.max(self.innerWidth || 0, document.documentElement.clientWidth || 0, document.body.clientWidth || 0);var windowWidth = self.innerWidth || -1; // 因为“body”或“screen”或“document”不是“window”如果你检查一个溢出的html内容你可以理解。 #i.stack.imgur.com/6xPdH.png
        • 示例中的复制粘贴错误,函数getWidth() 引用self.innerHeight
        【解决方案5】:

        为什么没人提到 matchMedia?

        if (window.matchMedia("(min-width: 400px)").matches) {
          /* the viewport is at least 400 pixels wide */
        } else {
          /* the viewport is less than 400 pixels wide */
        }
        

        没有测试那么多,但是用android默认和android chrome浏览器测试,桌面chrome,到目前为止看起来效果很好。

        当然它不返回数字值,而是返回布尔值 - 如果匹配或不匹配,所以可能不完全符合问题,但无论如何这就是我们想要的,可能问题的作者也想要。

        【讨论】:

        • 只支持IE10+。
        • 如果他们使用 IE9 或更低版本,他们不值得上网。
        • Safari iphone 似乎不支持这个。
        • 较新的 iOS Safari 版本应该支持 matchMedia。来源:caniuse.com/#feat=matchmedia
        【解决方案6】:

        从 W3schools 及其跨浏览器回到 IE 的黑暗时代!

        <!DOCTYPE html>
        <html>
        <body>
        
        <p id="demo"></p>
        
        <script>
        var w = window.innerWidth
        || document.documentElement.clientWidth
        || document.body.clientWidth;
        
        var h = window.innerHeight
        || document.documentElement.clientHeight
        || document.body.clientHeight;
        
        var x = document.getElementById("demo");
        x.innerHTML = "Browser inner window width: " + w + ", height: " + h + ".";
        
        alert("Browser inner window width: " + w + ", height: " + h + ".");
        
        </script>
        
        </body>
        </html>
        

        【讨论】:

        • 这种方法效果很好,可能是公认的答案,因为它比任何其他解决方案都要短得多(除了使用 jQuery)。
        • 如果 document.documentElement 未定义会不会报错?
        【解决方案7】:
        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() 返回无效值

        【讨论】:

        • 在 Safari iphone 上使用此功能时遇到问题。
        【解决方案8】:

        这是一个pain in the ass。我建议跳过废话并使用jQuery,这样您就可以使用$(window).width()

        【讨论】:

        • 如果我没记错的话,jQuery 已经将很多维度拉入了核心。您仍然需要维度来执行您的建议吗?
        • jQuery 中的 $(window).width() 支持从 1.2 版开始,以防它与任何人相关。
        • 我发现 $(window).width() 并不总是根据以下答案中的示例返回与 innerWidth / clientWidth 相同的值。 jQuery 的版本不考虑浏览器滚动条(无论如何在 FF 中)。这让我对 CSS @media 查询似乎以错误的宽度触发感到很困惑。使用本机代码似乎更可靠,因为它考虑了滚动条的外观。
        • 添加 30k 行代码来获取窗口宽度是一个糟糕的解决方案!
        • @codechimp "添加 30k 行代码来获取窗口宽度是一个糟糕的解决方案!"继续添加 80k 文件以获取窗口宽度。坏是相对的。
        【解决方案9】:

        以下是上述函数的简化版本:

        function getWidth() {
            if (self.innerWidth) {
               return self.innerWidth;
            }
            else if (document.documentElement && document.documentElement.clientHeight){
                return document.documentElement.clientWidth;
            }
            else if (document.body) {
                return document.body.clientWidth;
            }
            return 0;
        }
        

        【讨论】:

        • 如果所有条件都为假,则返回值失败。
        • 你不需要其他的 :)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-25
        • 1970-01-01
        • 2011-03-20
        相关资源
        最近更新 更多