Javascript 获取屏幕大小、当前网页和浏览器窗口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3437786/
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-08-23 04:36:58  来源:igfitidea点击:

Get the size of the screen, current web page and browser window

javascriptjquerylayoutcross-browser

提问by turtledove

How can I get windowWidth, windowHeight, pageWidth, pageHeight, screenWidth, screenHeight, pageX, pageY, screenX, screenYwhich will work in all major browsers?

我怎样才能得到windowWidth, , windowHeight, pageWidth, pageHeight, screenWidth, screenHeight, pageX, pageY, screenX,screenY它适用于所有主要浏览器?

screenshot describing which values are wanted

描述需要哪些值的屏幕截图

采纳答案by Ankit Jaiswal

You can get the size of the window or document with jQuery:

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

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

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

For screen size you can use the screenobject:

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

window.screen.height;
window.screen.width;

回答by sidonaldson

This has everything you need to know: Get viewport/window size

这有你需要知道的一切:获取视口/窗口大小

but in short:

但简而言之:

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

小提琴

Please stop editing this answer. It's been edited 22 times now by different people to match their code format preference. It's also been pointed out that this isn't required if you only want to target modern browsers - if so you only need the following:

请停止编辑此答案。它已经被不同的人编辑了 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);

回答by confile

Here is a cross browser solution with pure JavaScript(Source):

这是一个使用纯JavaScript( Source)的跨浏览器解决方案:

var width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

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

回答by Daniel W.

A non-jQuery way to get the available screen dimension. window.screen.width/heighthas already been put up, but for responsive webdesign and completeness sake I think its worth to mention those attributes:

获取可用屏幕尺寸的非 jQuery 方法。window.screen.width/height已经提出,但为了响应式网页设计和完整性的缘故,我认为值得一提的是这些属性:

alert(window.screen.availWidth);
alert(window.screen.availHeight);

http://www.quirksmode.org/dom/w3c_cssom.html#t10:

http://www.quirksmode.org/dom/w3c_cssom.html#t10

availWidthand availHeight- The available width and height on the screen (excluding OS taskbars and such).

AvailWidthavailHeight- 屏幕上的可用宽度和高度(不包括操作系统任务栏等)。

回答by Aabha Pandey

But when we talk about responsive screens and if we want to handle it using jQuery for some reason,

但是当我们谈论响应式屏幕时,如果我们出于某种原因想使用 jQuery 来处理它,

window.innerWidth, window.innerHeight

gives the correct measurement. Even it removes the scroll-bar's extra space and we don't need to worry about adjusting that space :)

给出正确的测量值。即使它删除了滚动条的额外空间,我们也无需担心调整该空间:)

回答by serfer2

You can also get the WINDOW width and height, avoiding browser toolbars and other stuff. It is the real usable area in browser's window.

您还可以获得 WINDOW 宽度和高度,避免浏览器工具栏和其他东西。它是浏览器窗口中真正可用的区域

To do this, use: window.innerWidthand window.innerHeightproperties (see doc at w3schools).

为此,请使用: window.innerWidthwindow.innerHeight属性(请参阅 w3schools 上的文档)。

In most cases it will be the best way, in example, to display a perfectly centred floating modal dialog. It allows you to calculate positions on window, no matter which resolution orientation or window size is using the browser.

在大多数情况下,这将是最好的方式,例如,显示一个完美居中的浮动模态对话框。它允许您计算窗口上的位置,无论浏览器使用的是哪种分辨率方向或窗口大小。

回答by dude

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

回答by solanki...

To check height and width of your current loaded page of any website using "console"or after clicking "Inspect".

使用“控制台”或单击“检查”检查任何网站当前加载页面的高度和宽度。

step 1: Click the right button of mouse and click on 'Inspect' and then click 'console'

步骤1:单击鼠标右键并单击“检查”,然后单击“控制台”

step 2: Make sure that your browser screen should be not in 'maximize' mode. If the browser screen is in 'maximize' mode, you need to first click the maximize button (present either at right or left top corner) and un-maximize it.

第 2 步:确保您的浏览器屏幕不处于“最大化”模式。如果浏览器屏幕处于“最大化”模式,您需要先单击最大化按钮(出现在右上角或左上角)并取消最大化。

step 3: Now, write the following after the greater than sign ('>') i.e.

第 3 步:现在,在大于号 ('>') 后写入以下内容,即

       > window.innerWidth
            output : your present window width in px (say 749)

       > window.innerHeight
            output : your present window height in px (say 359)

回答by hashchange

If you need a truly bulletproof solution for the document width and height (the pageWidthand pageHeightin the picture), you might want to consider using a plugin of mine, jQuery.documentSize.

如果您需要针对文档宽度和高度(图片中的pageWidthpageHeight)的真正防弹解决方案,您可能需要考虑使用我的插件jQuery.documentSize

It has just one purpose: to always return the correct document size, even in scenarios when jQuery and other methods fail. Despite its name, you don't necessarily have to use jQuery – it is written in vanilla Javascript and works without jQuery, too.

它只有一个目的:始终返回正确的文档大小,即使在 jQuery 和其他方法失败的情况下也是如此。尽管它的名字,你不一定必须使用 jQuery——它是用普通的 Javascript 编写的,也可以在没有 jQuery 的情况下工作

Usage:

用法:

var w = $.documentWidth(),
    h = $.documentHeight();

for the global document. For other documents, e.g. in an embedded iframe you have access to, pass the document as a parameter:

对于全球document。对于其他文档,例如在您有权访问的嵌入式 iframe 中,将文档作为参数传递:

var w = $.documentWidth( myIframe.contentDocument ),
    h = $.documentHeight( myIframe.contentDocument );

Update: now for window dimensions, too

更新:现在也是窗口尺寸

Ever since version 1.1.0, jQuery.documentSize also handles window dimensions.

从 1.1.0 版开始,jQuery.documentSize 也处理窗口尺寸。

That is necessary because

这是必要的,因为

  • $( window ).height()is buggy in iOS, to the point of being useless
  • $( window ).width()and $( window ).height()are unreliable on mobilebecause they don't handle the effects of mobile zooming.

jQuery.documentSize provides $.windowWidth()and $.windowHeight(), which solve these issues. For more, please check out the documentation.

jQuery.documentSize 提供了$.windowWidth()$.windowHeight(),解决了这些问题。有关更多信息,请查看文档

回答by Andi Giga

I wrote a small javascript bookmarklet you can use to display the size. You can easily add it to your browser and whenever you click it you will see the size in the right corner of your browser window.

我写了一个小的 javascript 书签,你可以用它来显示大小。您可以轻松地将其添加到浏览器中,无论何时单击它,您都会在浏览器窗口的右上角看到大小。

Here you find information how to use a bookmarklet https://en.wikipedia.org/wiki/Bookmarklet

在这里您可以找到有关如何使用书签的信息 https://en.wikipedia.org/wiki/Bookmarklet

Bookmarklet

小书签

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

Original Code

原始代码

The original code is in coffee:

原始代码在咖啡中:

(->
  addWindowSize = ()->
    style = 'background-color:azure; padding:1rem; position:fixed; right: 0; z-index:9999; font-size: 1.2rem;'
    $windowSize = $('<div style="' + style + '"></div>')

    getWindowSize = ->
      '<p style="margin:0;">width: ' + $(window).width() + ' height: ' + $(window).height() + '</p>'

    $windowSize.html getWindowSize()
    $('body').prepend $windowSize
    $(window).resize ->
      $windowSize.html getWindowSize()
      return

  if !($ = window.jQuery)
    # typeof jQuery=='undefined' works too
    script = document.createElement('script')
    script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'
    script.onload = addWindowSize
    document.body.appendChild script
  else
    $ = window.jQuery
    addWindowSize()
)()

Basically the code is prepending a small div which updates when you resize your window.

基本上,代码前面是一个小 div,它会在您调整窗口大小时更新。