javascript 屏幕宽度与可见部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4987309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:34:17  来源:igfitidea点击:

screen width vs visible portion

javascriptscreen

提问by med

I have a little problem with JavaScript, to get the screen width we use screen.width which returns the overall screen resolution, is there a command to get the resolution of the visible portion of the browser, like when the browser is not maximized?

我对 JavaScript 有一个小问题,为了获得屏幕宽度,我们使用 screen.width 返回整体屏幕分辨率,是否有一个命令来获取浏览器可见部分的分辨率,例如浏览器未最大化时?

回答by JCOC611

function width(){
   return window.innerWidth 
       || document.documentElement.clientWidth 
       || document.body.clientWidth 
       || 0;
}

function height(){
   return window.innerHeight 
       || document.documentElement.clientHeight 
       || document.body.clientHeight 
       || 0;
}

Use them to return the height()or width()of the visible window.

使用它们返回可见窗口的height()width()

JSFiddle example.

JSFiddle 示例。

回答by NT3RP

The area you're describing is the viewport, and can typically be accessed by using window.innerWidthor window.innerHeightin modern browsers. IE6 is a bit different, but more information on handling the viewport width for all browsers can be found in this tutorial on obtaining viewport size.

您所描述的区域是视口,通常可以通过在现代浏览器中使用window.innerWidthwindow.innerHeight来访问。IE6 有点不同,但有关处理所有浏览器的视口宽度的更多信息可以在获取视口大小的教程中找到。

回答by madaaah

I saw that the question was answered, but here is the code I used with an image to ilustrate.

我看到这个问题得到了回答,但这是我用图像来说明的代码。

function height(){
return(window.innerHeight)?
window.innerHeight:
document.documentElement.clientHeight||document.body.clientHeight||0;
}
$(document).ready(function(){
$('.first, .second').css('height',height());
});
$(window).resize(function() {
$('.first, .second').css('height',height());
});

JSFiddle Example

JSFiddle 示例