首页 文章

使用JavaScript获取浏览器视口尺寸

提问于
浏览
635

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

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

12 回答

  • 9

    如果你不使用jQuery,它会变得丑陋 . 这是一个应该适用于所有新浏览器的代码段 . IE中的Quirks模式和标准模式的行为不同 . 这照顾它 .

    var elem = (document.compatMode === "CSS1Compat") ? 
        document.documentElement :
        document.body;
    
    var height = elem.clientHeight;
    var width = elem.clientWidth;
    
  • 6

    这就是我这样做的方式,我在IE 8 - > 10,FF 35,Chrome 40中尝试了它,它将在所有现代浏览器(如定义window.innerWidth)和IE 8(没有窗口)中非常流畅 . innerWidth它也可以顺利运行,任何问题(如因溢出而闪烁:“隐藏”),请报告 . 我对视口高度并不感兴趣,因为我将此功能仅用于解决一些响应式工具,但它可能已实现 . 希望它有所帮助,我感谢您的意见和建议 .

    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)
      );
    }
    
  • 7

    jQuery dimension functions

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

  • 6

    我查看并找到了一种跨浏览器的方式:

    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>
    
  • 4

    此代码来自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);

  • 30

    跨浏览器@media(宽度)和@media(高度)值

    var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
    var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    

    window.innerWidth和.innerHeight

    • 获取包含滚动条的CSS viewport @media (width)@media (height)

    • initial-scale 和zoom variations可能导致移动值 wrongly 缩小到PPK调用的visual viewport并小于 @media
      由于本机舍入,

    • zoom可能导致值为1px
      在IE8中

    • undefined -

    document.documentElement.clientWidth和.clientHeight

    资源

  • 2

    我能够在JavaScript中找到一个明确的答案:The Definitive Guide,第6版,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") 的事实,一切看起来都不错 .

  • 100

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

    innerHeight vs outerHeight

  • 8

    如果您正在寻找非jQuery解决方案 that gives correct values in virtual pixels on mobile ,并且您认为普通 window.innerHeightdocument.documentElement.clientHeight 可以解决您的问题,请首先学习此链接:http://tripleodeon.com/wp-content/uploads/2011/12/table.html

    开发人员已经做了很好的测试,揭示了问题:您可以获得Android / iOS,横向/纵向,普通/高密度显示器的意外值 .

    我目前的答案不是银弹(// todo),而是警告那些将快速将任何给定解决方案从此线程复制粘贴到 生产环境 代码中的人 .

    我在移动设备上寻找虚拟像素的页面宽度,我发现唯一正常工作的代码是(出乎意料!) window.outerWidth . 我稍后会检查这个表,以便在我有时间的情况下给出高度,不包括导航栏 .

  • 1080

    符合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将是不可见的但占用一些空间,这将导致滚动条出现等 .

  • 10

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

  • 61

    我知道这有一个可以接受的答案,但我遇到了 clientWidth 无效的情况,因为iPhone(至少是我的)返回了980而不是320,所以我使用了 window.screen.width . 我正在使用现有网站,正在制作"responsive"并需要强制更大的浏览器使用不同的元视口 .

    希望这有助于某人,它可能不完美,但它适用于我对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);
    

相关问题