【问题标题】:How to get the browser viewport dimensions?如何获取浏览器视口尺寸?
【发布时间】:2010-11-17 21:33:41
【问题描述】:

我想让我的访问者能够看到高质量的图像,有什么方法可以检测窗口大小?

或者更好的是,JavaScript 浏览器的视口大小?在此处查看绿色区域:

【问题讨论】:

  • 我所做的是,将一个通常为 html 的元素设置为 100% 高度并获取其高度。简单的作品无处不在。
  • @MuhammadUmer 不错!如果您对尺寸感到沮丧(在没有 jQuery 的手机上您会遇到这种情况),您可以使用扩展的 html 标签的 getComputedStyle
  • 另外,您可以使用W 库,它处理跨浏览器视口检测;)

标签: javascript cross-browser viewport


【解决方案1】:

jQuery dimension functions

$(window).width()$(window).height()

【讨论】:

  • @allyourcode,不可能,jQuery is the answer to all
  • 这不是视口大小,而是整体文档大小。试试看。
  • 对于将其插件工具栏显示为具有固定位置的 HTML 的浏览器,此解决方案不起作用,尤其是如果您想在代码中使用顶部位置和百分比。
  • @AlejandroIglesias:不,我只是在这个 SO 页面上测试了它。 $(window).height(); 返回 536,而 $("html").height(); 返回 10599
  • 警告这些尺寸不包括滚动条(在不同的浏览器和平台上具有不同的尺寸),因此它们与 css 媒体查询不匹配这里的其他答案确实解决了这个问题。
【解决方案2】:

如果你不使用 jQuery,它会变得很丑。这是一个适用于所有新浏览器的 sn-p。 IE 中 Quirks 模式和标准模式的行为不同。这可以解决问题。

var elem = (document.compatMode === "CSS1Compat") ? 
    document.documentElement :
    document.body;

var height = elem.clientHeight;
var width = elem.clientWidth;

【讨论】:

  • 这不是给你页面的高度,而不是视口吗?这就是这个页面似乎表明的:developer.mozilla.org/en/DOM/element.clientHeight
  • 您在document.documentElement 元素上使用clientHeight,这将为您提供视口大小。要获取文档大小,您需要执行document.body.clientHeight。正如 Chetan 所解释的,这种行为适用于现代浏览器。这很容易测试。只需打开一个控制台并在几个打开的选项卡上输入document.documentElement.clientHeight
【解决方案3】:

您可以使用window.innerWidthwindow.innerHeight 属性。

【讨论】:

  • 即使这在 IE +1 中对图表不起作用:D。对于这样的问题,没有更多这些应该是犯罪。
  • @CMS document.documentElement.clientWidthwindow.innerWidth 更准确,支持更广泛
  • @ryanve 如果“更准确”的意思是“甚至没有远程做同样的事情”,那么是的:P
  • 火狐测试版?那是属于博物馆的东西。
  • @boxed 在移动 Safari 中,document.documentElement.clientWidth 给我视口宽度,而 window.innerWidth 给我文档宽度。是的,就是这样。
【解决方案4】:

跨浏览器 @media (width)@media (height)

const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0)
const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0)

window.innerWidthwindow.innerHeight

  • 获取 CSS viewport @media (width)@media (height),其中包括滚动条
  • initial-scale 和缩放 variations 可能会导致移动值错误地缩小到 PPK 所称的 visual viewport 并小于 @media
  • 由于原生四舍五入,缩放可能会导致值偏离 1 像素
  • undefined 在 IE8 中-

document.documentElement.clientWidth.clientHeight


资源

【讨论】:

  • @01100001 将$ 替换为verge。如果您想集成到 jQuery 中,请执行jQuery.extend(verge)。见:verge.airve.com/#static
  • 只是想提一下,在 IE8(可能还有其他)中,您必须在页面顶部添加 <!DOCTYPE html> 才能使代码正常工作。
  • 我对移动设备上的 clientWidth/Height 不满意,真的 tripleodeon.com/wp-content/uploads/2011/12/table.html
  • 除非我遗漏了什么,否则这个答案是错误的。至少在 Chrome 中,document.documentElement.clientHeight 返回页面高度,而window.innerHeight 返回视口高度。大不同。
  • 不同屏幕尺寸变量/解决方案现场测试:ryanve.com/lab/dimensions
【解决方案5】:

此代码来自http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/

function viewport() {
    var e = window, a = 'inner';
    if (!('innerWidth' in window )) {
        a = 'client';
        e = document.documentElement || document.body;
    }
    return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}

注意:要读取宽度,请使用console.log('viewport width'+viewport().width);

【讨论】:

    【解决方案6】:

    window.innerHeightdocument.documentElement.clientHeight 之间存在差异。第一个包括水平滚动条的高度。

    【讨论】:

    【解决方案7】:

    符合 W3C 标准的解决方案是创建一个透明 div(例如使用 JavaScript 动态),将其宽度和高度设置为 100vw/100vh(视口单位),然后获取其 offsetWidth 和 offsetHeight。之后,可以再次删除该元素。这在较旧的浏览器中不起作用,因为视口单元相对较新,但如果您不关心它们而是关心(即将成为)标准,那么您绝对可以这样做:

    var objNode = document.createElement("div");
    objNode.style.width  = "100vw";
    objNode.style.height = "100vh";
    document.body.appendChild(objNode);
    var intViewportWidth  = objNode.offsetWidth;
    var intViewportHeight = objNode.offsetHeight;
    document.body.removeChild(objNode);
    

    当然,你也可以设置 objNode.style.position = "fixed" 然后使用 100% 作为宽度/高度 - 这样应该有相同的效果,并且在一定程度上提高了兼容性。此外,将位置设置为固定通常可能是一个好主意,因为否则 div 将不可见但会占用一些空间,这将导致出现滚动条等。

    【讨论】:

    • 不幸的是,现实完全破坏了您的“W3C - 标准解决方案”:1)caniuse.com/viewport-units,2)caniuse.com/#feat=css-fixed。开发人员需要的是有效的解决方案,而不是“理论上应该有效”。
    • 如果我们可以依赖这些标准,那么我们甚至不需要所有那些跨浏览器解决方案。响应规范的解决方案不是解决方案。
    【解决方案8】:

    我知道这是一个可以接受的答案,但我遇到了clientWidth 不起作用的情况,因为 iPhone(至少我的)返回 980,而不是 320,所以我使用了window.screen.width。我在现有网站上工作,变得“响应式”,需要强制更大的浏览器使用不同的元视口。

    希望这对某人有所帮助,它可能并不完美,但它适用于我在 iOs 和 Android 上的测试。

    //sweet hack to set meta viewport for desktop sites squeezing down to mobile that are big and have a fixed width 
      //first see if they have window.screen.width avail
      (function() {
        if (window.screen.width)
        {
          var setViewport = {
            //smaller devices
            phone: 'width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no',
            //bigger ones, be sure to set width to the needed and likely hardcoded width of your site at large breakpoints  
            other: 'width=1045,user-scalable=yes',
            //current browser width
            widthDevice: window.screen.width,
            //your css breakpoint for mobile, etc. non-mobile first
            widthMin: 560,
            //add the tag based on above vars and environment 
            setMeta: function () {
              var params = (this.widthDevice <= this.widthMin) ? this.phone : this.other; 
              var head = document.getElementsByTagName("head")[0];
              var viewport = document.createElement('meta');
              viewport.setAttribute('name','viewport');
              viewport.setAttribute('content',params);
              head.appendChild(viewport);
            }
          }
          //call it 
          setViewport.setMeta();
        }
      }).call(this);
    

    【讨论】:

      【解决方案9】:

      我能够在 JavaScript: The Definitive Guide, 6th Edition by O'Reilly, p. 中找到明确的答案。 391:

      此解决方案即使在 Quirks 模式下也有效,而 ryanve 和 ScottEvernden 当前的解决方案则不行。

      function getViewportSize(w) {
      
          // Use the specified window or the current window if no argument
          w = w || window;
      
          // This works for all browsers except IE8 and before
          if (w.innerWidth != null) return { w: w.innerWidth, h: w.innerHeight };
      
          // For IE (or any browser) in Standards mode
          var d = w.document;
          if (document.compatMode == "CSS1Compat")
              return { w: d.documentElement.clientWidth,
                 h: d.documentElement.clientHeight };
      
          // For browsers in Quirks mode
          return { w: d.body.clientWidth, h: d.body.clientHeight };
      
      }
      

      除了我想知道为什么if (document.compatMode == "CSS1Compat") 不是if (d.compatMode == "CSS1Compat"),一切看起来都不错。

      【讨论】:

      • 您是在谈论 Retina 显示屏还是横向与纵向还是元视口标签?您不是指snowdragonledhk.com/… 中的虚拟像素?
      • 1) 当谈到高 DPI 显示器时,我指的是此处解释的虚拟像素:stackoverflow.com/a/14325619/139361。每个 iPhone 屏幕的宽度正好是 320 个虚拟像素。 2) 我说:a)documentElement.clientWidth 不响应 iOS 上的设备方向更改。 b) 显示物理像素数(实际上没用)而不是虚拟像素
      【解决方案10】:

      如果您正在寻找非 jQuery 解决方案在移动设备上提供正确的虚拟像素值,并且您认为普通的 window.innerHeightdocument.documentElement.clientHeight 可以解决您的问题,请研究此链接第一:https://tripleodeon.com/assets/2011/12/table.html

      开发人员进行了很好的测试,揭示了问题:对于 Android/iOS、横向/纵向、正常/高密度显示,您可以获得意想不到的值。

      我目前的答案还不是灵丹妙药 (//todo),而是对那些将要快速将任何给定解决方案从该线程复制粘贴到生产代码中的人的警告。

      我在移动设备上寻找以 虚拟像素 为单位的页面宽度,我发现唯一有效的代码是(出乎意料!)window.outerWidth。稍后我将检查此表,以找到正确的解决方案,给出不包括导航栏的高度,当我有时间时。

      【讨论】:

        【解决方案11】:

        我看了下,找到了跨浏览器的方式:

        function myFunction(){
          if(window.innerWidth !== undefined && window.innerHeight !== undefined) { 
            var w = window.innerWidth;
            var h = window.innerHeight;
          } else {  
            var w = document.documentElement.clientWidth;
            var h = document.documentElement.clientHeight;
          }
          var txt = "Page size: width=" + w + ", height=" + h;
          document.getElementById("demo").innerHTML = txt;
        }
        <!DOCTYPE html>
        <html>
          <body onresize="myFunction()" onload="myFunction()">
           <p>
            Try to resize the page.
           </p>
           <p id="demo">
            &nbsp;
           </p>
          </body>
        </html>

        【讨论】:

        • 请注意,stackoverflow 在代码 sn-p 周围使用 iframe 会弄乱结果
        • 我经常遇到一个直接影响解决方案和理解它如何工作的答案。我希望我能给这 10 个赞,而不是一个。为了使用 F12 移动模拟器以交互方式进行这项工作,我发现页面
        • @pghcpa 我希望我能给你的评论 10 票而不是 1 票。该元标记是救命稻草。
        【解决方案12】:

        我就是这样做的,我在 IE 8 -> 10、FF 35、Chrome 40 中尝试过,它在所有现代浏览器(定义为 window.innerWidth)和 IE 8(使用没有window.innerWidth)它也很流畅,任何问题(比如因为溢出而闪烁:“隐藏”),请报告。我对视口高度并不真正感兴趣,因为我制作此功能只是为了解决一些响应式工具,但它可能会被实现。希望对您有所帮助,感谢 cmets 和建议。

        function viewportWidth () {
          if (window.innerWidth) return window.innerWidth;
          var
          doc = document,
          html = doc && doc.documentElement,
          body = doc && (doc.body || doc.getElementsByTagName("body")[0]),
          getWidth = function (elm) {
            if (!elm) return 0;
            var setOverflow = function (style, value) {
              var oldValue = style.overflow;
              style.overflow = value;
              return oldValue || "";
            }, style = elm.style, oldValue = setOverflow(style, "hidden"), width = elm.clientWidth || 0;
            setOverflow(style, oldValue);
            return width;
          };
          return Math.max(
            getWidth(html),
            getWidth(body)
          );
        }
        

        【讨论】:

          【解决方案13】:

          如果您使用的是 React,那么使用最新版本的 react hooks,您可以使用它。

          // Usage
          function App() {
             const size = useWindowSize();
          
             return (
               <div>
                 {size.width}px / {size.height}px
               </div>
             );
           }
          

          https://usehooks.com/useWindowSize/

          【讨论】:

          • 完全矫枉过正
          【解决方案14】:

          你可以使用 window.addEventListener('resize' , yourfunction); 当窗口调整大小时,它将运行你的函数。 当您使用 window.innerWidthdocument.documentElement.clientWidth 时,它是只读的。 您可以在您的函数中使用 if 语句并使其变得更好。

          【讨论】:

            【解决方案15】:

            您可以简单地使用 JavaScript window.matchMedia() 方法根据 CSS 媒体查询检测移动设备。这是检测移动设备的最佳、最可靠的方法。

            以下示例将向您展示此方法的实际工作原理:

            <script>
            $(document).ready(function(){
                if(window.matchMedia("(max-width: 767px)").matches){
                    // The viewport is less than 768 pixels wide
                    alert("This is a mobile device.");
                } else{
                    // The viewport is at least 768 pixels wide
                    alert("This is a tablet or desktop.");
                }
            });
            </script>
            

            【讨论】:

              【解决方案16】:

              动态检测尺寸

              您可以在 Native 中完成,无需 Jquery 或其他功能

              console.log('height default :'+window.visualViewport.height)
              console.log('width default :'+window.visualViewport.width)
              
              window.addEventListener('resize',(e)=>{         
                    console.log( `width: ${e.target.visualViewport.width}px`);
                    console.log( `height: ${e.target.visualViewport.height}px`);
               });

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2020-01-28
                • 1970-01-01
                • 1970-01-01
                • 2023-03-27
                • 1970-01-01
                • 2011-11-13
                相关资源
                最近更新 更多