简体   繁体   English

如何获取浏览器屏幕的视口高度?

[英]How to get viewport height of screen of browser?

All questions I see answer: 我看到的所有问题都回答:

$(window).height();

But this returns not the size of viewport but size of page, for example if I style <body> to height 1000px this will return 1000 but not the size of view port. 但这不返回视口的大小,而是页面的大小,例如,如果我将<body>样式设置为高度1000px,则将返回1000,但不返回视口的大小。 I need size of viewport not the collective page size that is scroll able. 我需要视口的大小,而不是可以滚动的集合页面的大小。

You can try 你可以试试

<!DOCTYPE html>
<html>
<head>
<script>
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;
}
</script>
<body onresize="myFunction()" onload="myFunction()">
<p>
Try to resize the page.
</p>
<p id="demo">
&nbsp;
</p>
</body>
</html>
$(window).height();

should return the height of the viewport (even if you set the height of the body tag in pixels). 应该返回视口的高度(即使您以像素为单位设置body标签的高度)。 I also use: 我还使用:

var heightViewport = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

which has given me better accuracy on iOS especially. 特别是在iOS上,这给了我更好的准确性。

$(document).height();

should return the height of the document (hence the height of the body tag in your case). 应该返回文档的高度(因此您的情况下,body标签的高度)。

Are your sure you are not using document instead of window? 您确定不使用文档而不是窗口吗?

It will return the size of the viewport. 它将返回视口的大小。

$('#viewportDimensions').text($(window).width() + ', ' + $(window).height());

$(window).resize(function() {
  $('#viewportDimensions').text($(window).width() + ', ' + $(window).height());
});

resize page in fiddle 在小提琴中调整页面大小

try this: 尝试这个:

var w=window,d=document,e=d.documentElement,g=d.getElementsByTagName('body')[0];
var x=w.innerWidth||e.clientWidth||g.clientWidth;
var y=w.innerHeight||e.clientHeight||g.clientHeight;
    console.log(x,y);

main source: http://andylangton.co.uk/blog/development/get-viewport-size-width-and-height-javascript 主要来源: http : //andylangton.co.uk/blog/development/get-viewport-size-width-and-height-javascript

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM