如何获取浏览器视口尺寸?

发布于 2024-07-30 07:03:51 字数 220 浏览 5 评论 0原文

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

或者更好的是,使用 JavaScript 的浏览器的视口大小? 请参阅此处的绿色区域:

I want to provide my visitors the ability to see images in high quality, is there any way I can detect the window size?

Or better yet, the viewport size of the browser with JavaScript? See green area here:

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

烏雲後面有陽光 2024-08-06 07:03:51

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

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

window.innerWidthwindow.innerHeight

document.documentElement.clientWidth< /code>.clientHeight


资源

Cross-browser @media (width) and @media (height) values 

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

window.innerWidth and window.innerHeight

  • gets CSS viewport @media (width) and @media (height) which include scrollbars
  • initial-scale and zoom variations may cause mobile values to wrongly scale down to what PPK calls the visual viewport and be smaller than the @media values
  • zoom may cause values to be 1px off due to native rounding
  • undefined in IE8-

document.documentElement.clientWidth and .clientHeight


Resources

无力看清 2024-08-06 07:03:51

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

开发人员做了很好的测试,揭示了这个问题:对于 Android/iOS、横向/纵向、正常/高密度显示,您可能会得到意外的值。

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

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

If you are looking for non-jQuery solution that gives correct values in virtual pixels on mobile, and you think that plain window.innerHeight or document.documentElement.clientHeight can solve your problem, please study this link first: https://tripleodeon.com/assets/2011/12/table.html

The developer has done good testing that reveals the problem: you can get unexpected values for Android/iOS, landscape/portrait, normal/high density displays.

My current answer is not silver bullet yet (//todo), but rather a warning to those who are going to quickly copy-paste any given solution from this thread into production code.

I was looking for page width in virtual pixels on mobile, and I've found the only working code is (unexpectedly!) window.outerWidth. I will later examine this table for correct solution giving height excluding navigation bar, when I have time.

葵雨 2024-08-06 07:03:51

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

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">
     
   </p>
  </body>
</html>

I looked and found a cross browser way:

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">
     
   </p>
  </body>
</html>

太阳公公是暖光 2024-08-06 07:03:51

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

希望这对某人有帮助,它可能并不完美,但它在我的 iO 和 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);

I know this has an acceptable answer, but I ran into a situation where clientWidth didn't work, as iPhone (at least mine) returned 980, not 320, so I used window.screen.width. I was working on existing site, being made "responsive" and needed to force larger browsers to use a different meta-viewport.

Hope this helps someone, it may not be perfect, but it works in my testing on iOs and 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);
海未深 2024-08-06 07:03:51

我在 JavaScript: The Definitive Guide, 6th Edition by O'Reilly, p. 1 中找到了明确的答案。 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") 之外,一切看起来不错。

I was able to find a definitive answer in JavaScript: The Definitive Guide, 6th Edition by O'Reilly, p. 391:

This solution works even in Quirks mode, while ryanve and ScottEvernden's current solution do not.

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

}

except for the fact that I wonder why the line if (document.compatMode == "CSS1Compat") is not if (d.compatMode == "CSS1Compat"), everything looks good.

じее 2024-08-06 07:03:51

如果你不使用 jQuery,它会变得很难看。 这是一个适用于所有新浏览器的代码片段。 IE 中的怪异模式和标准模式的行为有所不同。 这可以解决它。

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

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

If you aren't using jQuery, it gets ugly. Here's a snippet that should work on all new browsers. The behavior is different in Quirks mode and standards mode in IE. This takes care of it.

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

var height = elem.clientHeight;
var width = elem.clientWidth;
太傻旳人生 2024-08-06 07:03:51

jQuery 维度函数

$(window).width() 和 <代码>$(窗口).height()

jQuery dimension functions

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

菊凝晚露 2024-08-06 07:03:51

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

innerHeight 与outerHeight

You can use the window.innerWidth and window.innerHeight properties.

innerHeight vs outerHeight

ㄟ。诗瑗 2024-08-06 07:03:51

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

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

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

https://usehooks.com/useWindowSize/

If you are using React, then with latest version of react hooks, you could use this.

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

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

https://usehooks.com/useWindowSize/

萧瑟寒风 2024-08-06 07:03:51

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

you can use
window.addEventListener('resize' , yourfunction);
it will runs yourfunction when the window resizes.
when you use window.innerWidth or document.documentElement.clientWidth it is read only.
you can use if statement in yourfunction and make it better.

月牙弯弯 2024-08-06 07:03:51

您只需使用 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>

You can simply use the JavaScript window.matchMedia() method to detect a mobile device based on the CSS media query. This is the best and most reliable way to detect mobile devices.

The following example will show you how this method actually works:

<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>
叹沉浮 2024-08-06 07:03:51

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

This code is from 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' ] };
}

NB : to read the width, use console.log('viewport width'+viewport().width);

何必那么矫情 2024-08-06 07:03:51

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

There is a difference between window.innerHeight and document.documentElement.clientHeight. The first includes the height of the horizontal scrollbar.

微凉 2024-08-06 07:03:51

为了动态检测大小,

您可以在本机中完成,无需 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`);
 });

For detect the Size dynamically

You can do it In Native away, without Jquery or extras

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

柏林苍穹下 2024-08-06 07:03:51

应该

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

It should be

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

understand viewport: https://developer.mozilla.org/en-US/docs/Web/CSS/Viewport_concepts

shorthand for link above: viewport.moz.one

I've built a site for testing on devices: https://vp.moz.one

怎樣才叫好 2024-08-06 07:03:51

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

A solution that would conform to W3C standards would be to create a transparent div (for example dynamically with JavaScript), set its width and height to 100vw/100vh (Viewport units) and then get its offsetWidth and offsetHeight. After that, the element can be removed again. This will not work in older browsers because the viewport units are relatively new, but if you don't care about them but about (soon-to-be) standards instead, you could definitely go this way:

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

Of course, you could also set objNode.style.position = "fixed" and then use 100% as width/height - this should have the same effect and improve compatibility to some extent. Also, setting position to fixed might be a good idea in general, because otherwise the div will be invisible but consume some space, which will lead to scrollbars appearing etc.

自此以后,行同陌路 2024-08-06 07:03:51

我就是这样做的,我在 IE 8 中尝试过 -> 10、FF 35、Chrome 40,它在所有现代浏览器中都可以非常流畅地工作(定义了 window.innerWidth),并且在 IE 8(没有 window.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)
  );
}

This is the way I do it, I tried it in IE 8 -> 10, FF 35, Chrome 40, it will work very smooth in all modern browsers (as window.innerWidth is defined) and in IE 8 (with no window.innerWidth) it works smooth as well, any issue (like flashing because of overflow: "hidden"), please report it. I'm not really interested on the viewport height as I made this function just to workaround some responsive tools, but it might be implemented. Hope it helps, I appreciate comments and suggestions.

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)
  );
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文