小编典典

JavaScript获取屏幕,当前网页和浏览器窗口的大小

spring

我怎样才能得到windowWidth,windowHeight,pageWidth,pageHeight,screenWidth,screenHeight,pageX,pageY,``screenX,screenY将在所有主要浏览器工作?


阅读 531

收藏
2020-04-23

共2个答案

小编典典

你可以使用jQuery获取窗口或文档的大小:

// Size of browser viewport.
$(window).height();
$(window).width();

// Size of HTML document (same as pageHeight/pageWidth in screenshot).
$(document).height();
$(document).width();

对于屏幕大小,你可以使用screen对象:

window.screen.height;
window.screen.width;
2020-04-23
小编典典

这包含你需要了解的所有信息:获取视口/窗口大小

简而言之:

var win = window,
    doc = document,
    docElem = doc.documentElement,
    body = doc.getElementsByTagName('body')[0],
    x = win.innerWidth || docElem.clientWidth || body.clientWidth,
    y = win.innerHeight|| docElem.clientHeight|| body.clientHeight;
alert(x + ' × ' + y);

Fiddle

请停止编辑此答案。根据不同的代码格式偏好,现在已对其进行了22次编辑。还指出了,如果你只想定位现代浏览器,则不需要这样做-如果是这样,则只需要以下内容:

const width  = window.innerWidth || document.documentElement.clientWidth || 
document.body.clientWidth;
const height = window.innerHeight|| document.documentElement.clientHeight|| 
document.body.clientHeight;

console.log(width, height);
2020-04-23