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

Ali*_*xel 724 javascript cross-browser viewport

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

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

rya*_*nve 1224

跨浏览器 @media (width)@media (height)价值观 

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

window.innerWidth.innerHeight

  • 获取CSS视口 @media (width),@media (height)其中包括滚动条
  • initial-scale和缩放变化可能会导致移动值错误地缩小到PPK调用视觉视口并小于@media
  • 由于本机舍入,缩放可能导致值为1px
  • undefined 在IE8-

document.documentElement.clientWidth.clientHeight

资源

  • 除非我遗漏了什么,否则这个答案是错误的.至少在Chrome中,`document.documentElement.clientHeight`返回**页面高度**,而`window.innerHeight`返回**视口高度**.很大的区别. (16认同)
  • 我对移动设备上的clientWidth/Height不满意,真的是http://tripleodeon.com/wp-content/uploads/2011/12/table.html (6认同)
  • @ 01100001用`verge`替换`$`.如果你想集成到jQuery然后做`jQuery.extend(verge)`.请参阅:http://verge.airve.com/#static (4认同)
  • 只是想提一下,在IE8(或许是其他人)中,你必须在页面顶部有`<!DOCTYPE html>`才能使代码正常工作. (4认同)
  • 不同屏幕尺寸变量/解决方案现场测试:https://ryanve.com/lab/dimensions/ (4认同)

Sco*_*den 105

jQuery维度函数

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

  • @allyourcode,不可能,[jQuery是所有人的答案](http://meta.stackexchange.com/questions/19478/the-many-memes-of-meta/19492#19492). (60认同)
  • 这不会获取视口大小,而是整个文档大小.试试吧. (21认同)
  • @AlejandroIglesias:不,我刚刚在这个SO页面上测试过它.`$(window).height();`返回536,而`$("html").height();`返回10599 (6认同)
  • 对于将其插件工具栏显示为具有固定postitionning的HTML的浏览器,此解决方案无效,尤其是如果要在代码顶部定位和百分比中使用. (2认同)
  • 警告这些维度不包括滚动条(在不同的浏览器和平台中具有不同的大小),因此它们不会与css媒体查询匹配,但是其他答案可以解决此问题. (2认同)

CMS*_*CMS 73

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

innerHeight vs outerHeight

  • 即使这在图表的IE +1中不起作用:D.对于这样的问题,如果没有更多这些问题应该是犯罪. (29认同)
  • 在IE中不起作用 - http://www.quirksmode.org/dom/w3c_cssom.html#windowview (11认同)
  • @CMS` document.documentElement.clientWidth`比`window.innerWidth`更准确,支持更广泛. (7认同)
  • @ryanve如果"更准确",你的意思是"甚至不会远程做同样的事情"那么是的:P (6认同)

Che*_*try 32

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

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

var height = elem.clientHeight;
var width = elem.clientWidth;
Run Code Online (Sandbox Code Playgroud)

  • 这不是给你页面的高度,而不是视口?这就是这个页面似乎表明的内容:https://developer.mozilla.org/en/DOM/element.clientHeight (8认同)
  • 您在`document.documentElement`元素上使用`clientHeight`,它将为您提供视口大小.要获得文档大小,您需要执行`document.body.clientHeight`.正如Chetan所解释的,这种行为适用于现代浏览器.它很容易测试.只需打开一个控制台,在几个打开的选项卡上键入`document.documentElement.clientHeight`即可. (3认同)

Jaz*_*zzy 13

我知道这有一个可以接受的答案,但我遇到了一个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);
Run Code Online (Sandbox Code Playgroud)


nop*_*ole 12

我能够在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 };

}
Run Code Online (Sandbox Code Playgroud)

除了我想知道为什么这条线if (document.compatMode == "CSS1Compat")没有的事实if (d.compatMode == "CSS1Compat"),一切看起来都不错.


小智 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;
}
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html>
  <body onresize="myFunction()" onload="myFunction()">
   <p>
    Try to resize the page.
   </p>
   <p id="demo">
    &nbsp;
   </p>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)


小智 11

用于动态检测大小

你可以在 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`);
 });
Run Code Online (Sandbox Code Playgroud)

  • Microsoft 不支持 IE(任何版本)。现在可以安全地将它放入盒子中并埋在花园的尽头。 (2认同)

小智 9

此代码来自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' ] };
}
Run Code Online (Sandbox Code Playgroud)

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


小智 9

window.innerHeight和之间有区别document.documentElement.clientHeight.第一个包括水平滚动条的高度.


Dan*_*Dan 9

如果您正在寻找能够在移动设备上为虚拟像素提供正确值的非jQuery解决方案,并且您认为这很简单window.innerHeightdocument.documentElement.clientHeight可以解决您的问题,请首先学习此链接:http://tripleodeon.com/wp-content/uploads/十二分之二千零十一/ table.html

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

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

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

  • 我得到了404链接. (6认同)

ini*_*itd 8

它应该是

let vw = document.documentElement.clientWidth;
let vh = document.documentElement.clientHeight;
Run Code Online (Sandbox Code Playgroud)

了解视口:https ://developer.mozilla.org/en-US/docs/Web/CSS/Viewport_concepts

上面链接的简写:viewport.moz.one

我建立了一个用于在设备上进行测试的网站:https: //vp.moz.one


小智 6

符合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);
Run Code Online (Sandbox Code Playgroud)

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


小智 5

这就是我这样做的方式,我在 IE 8 -> 10、FF 35、Chrome 40 中尝试过,它在所有现代浏览器(定义了 window.innerWidth)和 IE 8(没有 window.innerWidth)中都可以非常流畅地工作。 insideWidth)它也运行顺利,任何问题(例如由于溢出:“隐藏”而闪烁),请报告它。我对视口高度并不是很感兴趣,因为我创建这个函数只是为了解决一些响应式工具,但它可能会被实现。希望它有帮助,我感谢评论和建议。

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)
  );
}
Run Code Online (Sandbox Code Playgroud)