937

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

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

4

17 回答 17

1567

跨浏览器 @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 视口 @media (width)@media (height)其中包括滚动条
  • initial-scale和缩放变化可能会导致移动值错误地缩小到 PPK 所谓的视觉视口并小于@media
  • 由于本机舍入,缩放可能会导致值偏离 1px
  • undefined在 IE8-

document.documentElement.clientWidth.clientHeight


资源

于 2012-01-16T05:23:11.690 回答
117

jQuery 维度函数

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

于 2009-08-08T06:01:22.467 回答
88

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

内部高度与外部高度

于 2009-08-08T06:39:12.733 回答
35

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

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

var height = elem.clientHeight;
var width = elem.clientWidth;
于 2009-08-08T06:20:10.510 回答
19

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

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>

于 2014-05-30T09:07:01.847 回答
16

我知道这是一个可以接受的答案,但我遇到了一个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);
于 2013-08-12T19:12:47.987 回答
12

我能够在 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"),一切看起来都很好。

于 2013-08-17T01:18:49.520 回答
12

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

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

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

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

于 2014-05-13T17:12:30.840 回答
11

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

于 2012-12-31T08:01:04.333 回答
10

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

于 2013-02-16T21:31:36.807 回答
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 将不可见但会占用一些空间,这将导致出现滚动条等。

于 2013-05-05T21:16:18.360 回答
4

这就是我这样做的方式,我在 IE 8 -> 10、FF 35、Chrome 40 中尝试过,它在所有现代浏览器(定义为 window.innerWidth)和 IE 8(没有 window.innerWidth)中都非常流畅。 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)
  );
}
于 2015-02-24T11:57:56.953 回答
3

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

// Usage
function App() {
   const size = useWindowSize();

   return (
     <div>
       {size.width}px / {size.height}px
     </div>
   );
 }

https://usehooks.com/useWindowSize/

于 2020-09-11T16:36:44.620 回答
2

用于动态检测大小

您可以在 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`);
 });

于 2021-10-11T18:18:26.447 回答
1

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

于 2020-10-28T19:35:09.940 回答
1

您可以简单地使用 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>
于 2021-05-15T06:38:15.017 回答
0

它应该是

let vw = document.documentElement.clientWidth;
let vh = document.documentElement.clientHeight;

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

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

我已经建立了一个在设备上进行测试的站点:https ://vp.moz.one

于 2022-02-07T17:01:49.380 回答