如何获取windowWidth
,windowHeight
,pageWidth
,pageHeight
,screenWidth
,screenHeight
,pageX
,{ {1}},pageY
,screenX
哪些适用于所有主流浏览器?
答案 0 :(得分:1271)
如果您使用的是jQuery,则可以使用jQuery方法获取窗口或文档的大小:
$(window).height(); // returns height of browser viewport
$(document).height(); // returns height of HTML document (same as pageHeight in screenshot)
$(window).width(); // returns width of browser viewport
$(document).width(); // returns width of HTML document (same as pageWidth in screenshot)
对于屏幕尺寸,您可以通过以下方式使用screen
对象:
screen.height;
screen.width;
答案 1 :(得分:890)
这包含您需要知道的一切:Get viewport/window size
但简而言之:
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight|| e.clientHeight|| g.clientHeight;
alert(x + ' × ' + y);
<强> Fiddle 强>
答案 2 :(得分:435)
这是一个纯粹的 JavaScript (Source)的跨浏览器解决方案:
var width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var height = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
答案 3 :(得分:86)
获取可用屏幕尺寸的非jQuery方法。 window.screen.width/height
已被提出,但为了响应网页设计和完整性,我认为值得提及这些属性:
alert(window.screen.availWidth);
alert(window.screen.availHeight);
http://www.quirksmode.org/dom/w3c_cssom.html#t10:
availWidth 和 availHeight - 可用的宽度和高度 屏幕(不包括OS任务栏等)。
答案 4 :(得分:60)
但是当我们讨论响应式屏幕时,如果我们想因某些原因使用jQuery来处理它,
window.innerWidth, window.innerHeight
给出正确的测量结果。即使它删除了滚动条的额外空间,我们也不必担心调整空间:)
答案 5 :(得分:19)
令我惊讶的是,这个问题已有10年了,到目前为止,似乎还没有人给出完整的答案(有10个值)。所以我仔细分析了OP的问题(尤其是图片)并作了一些评论
(0,0)
的中心位于视口(没有条形和主边框的浏览器窗口)的左上角,并且轴指向右和向下(在OP图片上标记的位置),因此{{ 1}}必须为负(如果页面较小或未滚动,则为零)pageX, pageY, screenX, screenY
,OP希望统计屏幕的高度/宽度,包括系统菜单栏(例如,在MacO中)-这就是为什么我们不使用screenHeight/Width
(不对其进行计数)的原因.availWidth/Height
OP,我们不想计算滚动条的大小,因此我们使用windowWidth/Height
.clientWidth/Height
-在下面的解决方案中,我们将其菜单/表格/网址栏的高度添加到浏览器左上角(screenY
)的位置。但是,如果在浏览器中出现下载底部栏和/或在页面底部打开了开发者控制台,则很难计算该值-在这种情况下,以下解决方案中该栏/控制台高度的大小将增加。可能无法读取条形/控制台的高度值来进行校正(没有一些技巧,例如要求用户在测量之前关闭该条形/控制台...)window.screenY
-如果pageWidth小于windowWidth,我们需要手动计算pageWidth
子元素的大小以获取该值(我们在下面的解决方案中的<body>
中进行示例计算-但总的来说,在这种情况下可能很困难contentWidth
边距= 0-如果不是,那么在计算<body>
和pageWidth/Height
时应考虑此值
pageX/Y
function sizes() {
let contentWidth = [...document.body.children].reduce(
(a, el) => Math.max(a, el.getBoundingClientRect().right), 0)
- document.body.getBoundingClientRect().x;
return {
windowWidth: document.documentElement.clientWidth,
windowHeight: document.documentElement.clientHeight,
pageWidth: Math.min(document.body.scrollWidth, contentWidth),
pageHeight: document.body.scrollHeight,
screenWidth: window.screen.width,
screenHeight: window.screen.height,
pageX: document.body.getBoundingClientRect().x,
pageY: document.body.getBoundingClientRect().y,
screenX: -window.screenX,
screenY: -window.screenY - (window.outerHeight-window.innerHeight),
}
}
// TEST
function show() {
console.log(sizes());
}
body { margin: 0 }
.box { width: 3000px; height: 4000px; background: red; }
我在MacOs High Sierra上的Chrome 83.0,Safari 13.1,Firefox 77.0和Edge 83.0上进行了测试
答案 6 :(得分:18)
使用&#34; console&#34; 或点击&#34;检查&#34; 检查任何网站当前加载页面的高度和宽度
第1步:点击鼠标右键,然后点击&#39;检查&#39;然后点击“控制台”
第2步:确保您的浏览器屏幕不应该最大化&#39;模式。如果浏览器屏幕处于最大化状态&#39;在模式下,您需要先单击最大化按钮(出现在右上角或左上角)并取消最大化。
第3步:现在,在大于号后面写下以下内容(&#39;&gt;&#39;),即
> window.innerWidth
output : your present window width in px (say 749)
> window.innerHeight
output : your present window height in px (say 359)
答案 7 :(得分:17)
function wndsize(){
var w = 0;var h = 0;
//IE
if(!window.innerWidth){
if(!(document.documentElement.clientWidth == 0)){
//strict mode
w = document.documentElement.clientWidth;h = document.documentElement.clientHeight;
} else{
//quirks mode
w = document.body.clientWidth;h = document.body.clientHeight;
}
} else {
//w3c
w = window.innerWidth;h = window.innerHeight;
}
return {width:w,height:h};
}
function wndcent(){
var hWnd = (arguments[0] != null) ? arguments[0] : {width:0,height:0};
var _x = 0;var _y = 0;var offsetX = 0;var offsetY = 0;
//IE
if(!window.pageYOffset){
//strict mode
if(!(document.documentElement.scrollTop == 0)){offsetY = document.documentElement.scrollTop;offsetX = document.documentElement.scrollLeft;}
//quirks mode
else{offsetY = document.body.scrollTop;offsetX = document.body.scrollLeft;}}
//w3c
else{offsetX = window.pageXOffset;offsetY = window.pageYOffset;}_x = ((wndsize().width-hWnd.width)/2)+offsetX;_y = ((wndsize().height-hWnd.height)/2)+offsetY;
return{x:_x,y:_y};
}
var center = wndcent({width:350,height:350});
document.write(center.x+';<br>');
document.write(center.y+';<br>');
document.write('<DIV align="center" id="rich_ad" style="Z-INDEX: 10; left:'+center.x+'px;WIDTH: 350px; POSITION: absolute; TOP: '+center.y+'px; HEIGHT: 350px"><!--К сожалению, у Вас не установлен flash плеер.--></div>');
答案 8 :(得分:17)
您还可以获取WINDOW的宽度和高度,避免使用浏览器工具栏和其他内容。它是浏览器窗口中实际可用区域。
为此,请使用:
window.innerWidth
和window.innerHeight
属性(see doc at w3schools)。
在大多数情况下,显示完美居中的浮动模态对话框将是最佳方式。它允许您计算窗口上的位置,无论使用浏览器的分辨率方向或窗口大小。
答案 9 :(得分:10)
如果您需要一个真正的防弹解决方案来处理文档的宽度和高度(图片中的pageWidth
和pageHeight
),您可能需要考虑使用我的插件jQuery.documentSize 。
它只有一个目的:始终返回正确的文档大小,即使在jQuery和其他方法fail的情况下也是如此。尽管它的名字,你不一定要使用jQuery - 它也是用vanilla Javascript和works without jQuery编写的。
用法:
var w = $.documentWidth(),
h = $.documentHeight();
全局document
的。对于其他文件,例如在您有权访问的嵌入式iframe中,将文档作为参数传递:
var w = $.documentWidth( myIframe.contentDocument ),
h = $.documentHeight( myIframe.contentDocument );
更新:现在也适用于窗口尺寸
自版本1.1.0起,jQuery.documentSize也处理窗口尺寸。
这是必要的,因为
$( window ).height()
是buggy in iOS,无法使用$( window ).width()
和$( window ).height()
为unreliable on mobile因为它们无法处理移动缩放的影响。 jQuery.documentSize提供了解决这些问题的$.windowWidth()
和$.windowHeight()
。有关详情,请查看the documentation。
答案 10 :(得分:8)
我写了一个小的javascript书签,你可以用它来显示大小。您可以轻松地将其添加到浏览器中,每当您单击它时,您将在浏览器窗口的右上角看到大小。
在这里,您可以找到有关如何使用书签的信息 https://en.wikipedia.org/wiki/Bookmarklet
$top_reviews = $reviews()->orderBy('up_vote', '-', 'down_vote','DESC')->get();
原始代码在咖啡中:
javascript:(function(){!function(){var i,n,e;return n=function(){var n,e,t;return t="background-color:azure; padding:1rem; position:fixed; right: 0; z-index:9999; font-size: 1.2rem;",n=i('<div style="'+t+'"></div>'),e=function(){return'<p style="margin:0;">width: '+i(window).width()+" height: "+i(window).height()+"</p>"},n.html(e()),i("body").prepend(n),i(window).resize(function(){n.html(e())})},(i=window.jQuery)?(i=window.jQuery,n()):(e=document.createElement("script"),e.src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js",e.onload=n,document.body.appendChild(e))}()}).call(this);
基本上代码前面有一个小div,当你调整窗口大小时会更新。
答案 11 :(得分:6)
答案 12 :(得分:5)
在某些与响应式布局$(document).height()
相关的情况下,只能返回显示视图端口高度的错误数据。
例如,当某个div#wrapper的高度为100%时,#wrapper可以被其中的某个块拉伸。但它的高度仍然像视口高度。在这种情况下,您可以使用
$('#wrapper').get(0).scrollHeight
表示包装器的实际大小。
答案 13 :(得分:4)
我开发了一个用于了解桌面和移动浏览器的实际视口大小的库,因为视口大小在设备之间是不一致的,并且不能依赖于该帖子的所有答案(根据我对此所做的所有研究):{{ 3}}
答案 14 :(得分:3)
随着ES2020中globalThis
的引入,您可以使用类似的属性。
对于屏幕尺寸:
globalThis.screen.availWidth
globalThis.screen.availHeight
用于窗口大小
globalThis.outerWidth
globalThis.outerHeight
偏移量:
globalThis.pageXOffset
globalThis.pageYOffset
...&等等。
alert("Screen Width: "+ globalThis.screen.availWidth +"\nScreen Height: "+ globalThis.screen.availHeight)
答案 15 :(得分:3)
有时你需要在调整窗口和内部内容的大小时看到宽度/高度的变化。
为此我写了一个小脚本,添加了一个动态监视所有大小调整和几乎立即更新的日志框。
它添加了一个固定位置和高z-index的有效HTML,但足够小,所以你可以:
测试:Chrome 40,IE11,但很有可能在其他/旧浏览器上工作......:)
function gebID(id){ return document.getElementById(id); }
function gebTN(tagName, parentEl){
if( typeof parentEl == "undefined" ) var parentEl = document;
return parentEl.getElementsByTagName(tagName);
}
function setStyleToTags(parentEl, tagName, styleString){
var tags = gebTN(tagName, parentEl);
for( var i = 0; i<tags.length; i++ ) tags[i].setAttribute('style', styleString);
}
function testSizes(){
gebID( 'screen.Width' ).innerHTML = screen.width;
gebID( 'screen.Height' ).innerHTML = screen.height;
gebID( 'window.Width' ).innerHTML = window.innerWidth;
gebID( 'window.Height' ).innerHTML = window.innerHeight;
gebID( 'documentElement.Width' ).innerHTML = document.documentElement.clientWidth;
gebID( 'documentElement.Height' ).innerHTML = document.documentElement.clientHeight;
gebID( 'body.Width' ).innerHTML = gebTN("body")[0].clientWidth;
gebID( 'body.Height' ).innerHTML = gebTN("body")[0].clientHeight;
}
var table = document.createElement('table');
table.innerHTML =
"<tr><th>SOURCE</th><th>WIDTH</th><th>x</th><th>HEIGHT</th></tr>"
+"<tr><td>screen</td><td id='screen.Width' /><td>x</td><td id='screen.Height' /></tr>"
+"<tr><td>window</td><td id='window.Width' /><td>x</td><td id='window.Height' /></tr>"
+"<tr><td>document<br>.documentElement</td><td id='documentElement.Width' /><td>x</td><td id='documentElement.Height' /></tr>"
+"<tr><td>document.body</td><td id='body.Width' /><td>x</td><td id='body.Height' /></tr>"
;
gebTN("body")[0].appendChild( table );
table.setAttribute(
'style',
"border: 2px solid black !important; position: fixed !important;"
+"left: 50% !important; top: 0px !important; padding:10px !important;"
+"width: 150px !important; font-size:18px; !important"
+"white-space: pre !important; font-family: monospace !important;"
+"z-index: 9999 !important;background: white !important;"
);
setStyleToTags(table, "td", "color: black !important; border: none !important; padding: 5px !important; text-align:center !important;");
setStyleToTags(table, "th", "color: black !important; border: none !important; padding: 5px !important; text-align:center !important;");
table.style.setProperty( 'margin-left', '-'+( table.clientWidth / 2 )+'px' );
setInterval( testSizes, 200 );
编辑:现在样式仅应用于记录器表元素 - 而不是所有表 - 这也是 jQuery-free 解决方案:)
答案 16 :(得分:2)
您可以使用Screen对象来获取此内容。
以下是它将返回的示例:
Screen {
availWidth: 1920,
availHeight: 1040,
width: 1920,
height: 1080,
colorDepth: 24,
pixelDepth: 24,
top: 414,
left: 1920,
availTop: 414,
availLeft: 1920
}
要获取screenWidth
变量,只需使用screen.width
,与screenHeight
相同,您只需使用screen.height
。
要获得窗口宽度和高度,它们将分别为screen.availWidth
或screen.availHeight
。
对于pageX
和pageY
变量,请使用window.screenX or Y
。请注意,这是来自左侧/最左侧屏幕的非常左/右。因此,如果您有两个宽度为1920
的屏幕,则右屏幕左侧500px的窗口将具有2420
(1920 + 500)的X值。但是,screen.width/height
会显示CURRENT屏幕的宽度或高度。
要获取网页的宽度和高度,请使用jQuery&#39; $(window).height()
或$(window).width()
。
再次使用jQuery,对$("html").offset().top
和$("html").offset().left
值使用pageX
和pageY
。
答案 17 :(得分:2)
与屏幕尺寸有关的完整指南
JavaScript
高度:
document.body.clientHeight // Inner height of the HTML document body, including padding
// but not the horizontal scrollbar height, border, or margin
screen.height // Device screen height (i.e. all physically visible stuff)
screen.availHeight // Device screen height minus the operating system taskbar (if present)
window.innerHeight // The current document's viewport height, minus taskbars, etc.
window.outerHeight // Height the current window visibly takes up on screen
// (including taskbars, menus, etc.)
注意:当窗口最大化时,它将等于screen.availHeight
宽度:
document.body.clientWidth // Full width of the HTML page as coded, minus the vertical scroll bar
screen.width // Device screen width (i.e. all physically visible stuff)
screen.availWidth // Device screen width, minus the operating system taskbar (if present)
window.innerWidth // The browser viewport width (including vertical scroll bar, includes padding but not border or margin)
window.outerWidth // The outer window width (including vertical scroll bar,
// toolbars, etc., includes padding and border but not margin)
jQuery
高度:
$(document).height() // Full height of the HTML page, including content you have to
// scroll to see
$(window).height() // The current document's viewport height, minus taskbars, etc.
$(window).innerHeight() // The current document's viewport height, minus taskbars, etc.
$(window).outerHeight() // The current document's viewport height, minus taskbars, etc.
宽度:
$(document).width() // The browser viewport width, minus the vertical scroll bar
$(window).width() // The browser viewport width (minus the vertical scroll bar)
$(window).innerWidth() // The browser viewport width (minus the vertical scroll bar)
$(window).outerWidth() // The browser viewport width (minus the vertical scroll bar)
答案 18 :(得分:0)
// innerWidth
const screen_viewport_inner = () => {
let w = window,
i = `inner`;
if (!(`innerWidth` in window)) {
i = `client`;
w = document.documentElement || document.body;
}
return {
width: w[`${i}Width`],
height: w[`${i}Height`]
}
};
// outerWidth
const screen_viewport_outer = () => {
let w = window,
o = `outer`;
if (!(`outerWidth` in window)) {
o = `client`;
w = document.documentElement || document.body;
}
return {
width: w[`${o}Width`],
height: w[`${o}Height`]
}
};
// style
const console_color = `
color: rgba(0,255,0,0.7);
font-size: 1.5rem;
border: 1px solid red;
`;
// testing
const test = () => {
let i_obj = screen_viewport_inner();
console.log(`%c screen_viewport_inner = \n`, console_color, JSON.stringify(i_obj, null, 4));
let o_obj = screen_viewport_outer();
console.log(`%c screen_viewport_outer = \n`, console_color, JSON.stringify(o_obj, null, 4));
};
// IIFE
(() => {
test();
})();
答案 19 :(得分:0)
这是我如何在React JS Project中获取屏幕宽度的方法:
如果宽度等于1680,则返回570,否则返回200
var screenWidth = window.screen.availWidth;
<Label style={{ width: screenWidth == "1680" ? 570 : 200, color: "transparent" }}>a </Label>
答案 20 :(得分:-1)
我们现在可以安全地单独使用所有浏览器中的原生javascript窗口api ,而不使用窗口上下文。
语法有点清楚!
n = "<i>px</i><br>" /* separator */
dp = devicePixelRatio /* device zoom level */
body = (() => { document.body.innerHTML = /* ready! */
"Device zoom level: " + dp
+n+ "Screen width: " + screen.width
*dp+n+ "Screen height: "+ screen.height
*dp+n+ "Document frame height: " + innerHeight
*dp+n+ "Document frame width: " + innerWidth *dp+n+ "Parent document height: "+ outerHeight *dp+n+ "Parent document width: "+ outerWidth *dp+n+ "Window available height: "+ screen.availHeight *dp+n+ "Window available width: "+ screen.availWidth *dp+n+ "Document frame max scrollable X: "+ scrollMaxX *dp+n+ "Document frame max scrollable Y: "+ scrollMaxY
*dp+n+ "Distance from left screen to window: "+ screenX
*dp+n+ "Distance from top screen to window: "+ screenY
*dp+n
})()
要在每个浏览器和设备中获得准确的结果,必须将结果乘以 devicePixelRatio 。
Window属性devicePixelRatio返回的比率 物理像素的分辨率为CSS像素的分辨率 当前的显示设备。该值也可以解释为 像素大小的比例:一个CSS像素的大小与一个大小的大小 物理像素。简单来说,这告诉浏览器有多少 屏幕的实际像素应该用于绘制单个CSS像素。
这在处理渲染上的差异时非常有用 标准显示屏与HiDPI或Retina显示屏相比,使用更多 屏幕像素可以绘制相同的对象,从而产生更清晰的图像。
更改此值时无法通知(可以 例如,如果用户将窗口拖动到具有a的显示器,则会发生 不同的像素密度)。由于没有回调或事件 可用于检测像素密度变化,唯一的方法是 定期检查devicePixelRatio的值以查看它是否是 改变。只是不要经常这样做,否则你会影响表现。
https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio