Como posso obter windowWidth, windowHeight, pageWidth, pageHeight, screenWidth, screenHeight, pageX, pageY, screenX, screenYque irá funcionar em todos os principais navegadores?

Como posso obter windowWidth, windowHeight, pageWidth, pageHeight, screenWidth, screenHeight, pageX, pageY, screenX, screenYque irá funcionar em todos os principais navegadores?

Respostas:
Você pode obter o tamanho da janela ou documento com o jQuery:
// Size of browser viewport.
$(window).height();
$(window).width();
// Size of HTML document (same as pageHeight/pageWidth in screenshot).
$(document).height();
$(document).width();
Para o tamanho da tela, você pode usar o screenobjeto:
window.screen.height;
window.screen.width;
46) em vez de uma string como css ('height') ( "46px").
Isso tem tudo o que você precisa saber: obter tamanho da janela de exibição / janela
mas em resumo:
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);
Pare de editar esta resposta. Agora, ela foi editada 22 vezes por pessoas diferentes para corresponder à sua preferência de formato de código. Também foi apontado que isso não é necessário se você deseja segmentar apenas navegadores modernos - nesse caso, você só precisa do seguinte:
const width = window.innerWidth || document.documentElement.clientWidth ||
document.body.clientWidth;
const height = window.innerHeight|| document.documentElement.clientHeight||
document.body.clientHeight;
console.log(width, height);
g = document.body?
document.body.
Aqui está uma solução de navegador cruzado com JavaScript puro ( fonte ):
var width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var height = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
body elementvalor retornará undefinedcomo o dom ainda não foi carregado.
Uma maneira não-jQuery de obter a dimensão da tela disponível. window.screen.width/heightjá foi apresentado, mas, por um design responsivo e integridade, acho que vale a pena mencionar esses atributos:
alert(window.screen.availWidth);
alert(window.screen.availHeight);
http://www.quirksmode.org/dom/w3c_cssom.html#t10 :
availWidth e availHeight - A largura e altura disponíveis na tela (excluindo barras de tarefas do SO).
window.screen.availHeightparece assumir o modo de tela cheia para que o modo de tela normal force a rolagem (testado no Firefox e Chrome).
window.screen.height.
Mas quando falamos sobre telas responsivas e se queremos lidar com isso usando jQuery por algum motivo,
window.innerWidth, window.innerHeight
dá a medida correta. Mesmo ele remove o espaço extra da barra de rolagem e não precisamos nos preocupar em ajustar esse espaço :)
window.innerWidthe window.innerHeightnão consideramos o tamanho da barra de rolagem. Se houver barras de rolagem, esses métodos retornam resultados incorretos para o tamanho da janela em quase todos os navegadores da área de trabalho. Veja stackoverflow.com/a/31655549/508355
Você também pode obter a largura e a altura da JANELA, evitando barras de ferramentas do navegador e outras coisas. É a verdadeira área útil na janela do navegador .
Para fazer isso, use:
window.innerWidth and window.innerHeightproperties ( consulte o documento em w3schools ).
Na maioria dos casos, será a melhor maneira, por exemplo, de exibir um diálogo modal flutuante perfeitamente centralizado. Permite calcular posições na janela, independentemente da orientação da resolução ou tamanho da janela usando o navegador.
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>');
Para verificar a altura e a largura da página carregada atual de qualquer site usando o "console" ou depois de clicar em "Inspecionar" .
passo 1 : clique no botão direito do mouse, clique em 'Inspecionar' e, em seguida, clique em 'console'
passo 2 : verifique se a tela do navegador não está no modo 'maximizar'. Se a tela do navegador estiver no modo 'maximizar', você deverá primeiro clicar no botão maximizar (presente no canto superior direito ou esquerdo) e des maximizá-lo.
etapa 3 : Agora, escreva o seguinte após o sinal de maior que ('>')
> window.innerWidth
output : your present window width in px (say 749)
> window.innerHeight
output : your present window height in px (say 359)
Se você precisar de uma solução verdadeiramente à prova de balas para a largura e altura do documento (a pageWidthe pageHeightna figura), considere usar um plugin meu, jQuery.documentSize .
Ele tem apenas um objetivo: sempre retornar o tamanho correto do documento, mesmo em cenários em que o jQuery e outros métodos falham . Apesar do nome, você não precisa necessariamente usar o jQuery - ele é escrito em Javascript baunilha e funciona sem o jQuery também.
Uso:
var w = $.documentWidth(),
h = $.documentHeight();
para o global document. Para outros documentos, por exemplo, em um iframe incorporado ao qual você tem acesso, passe o documento como um parâmetro:
var w = $.documentWidth( myIframe.contentDocument ),
h = $.documentHeight( myIframe.contentDocument );
Atualização: agora também para as dimensões da janela
Desde a versão 1.1.0, o jQuery.documentSize também lida com as dimensões da janela.
Isso é necessário porque
$( window ).height()é buggy no iOS , a ponto de ser inútil$( window ).width()e não$( window ).height() são confiáveis no celular porque não lidam com os efeitos do zoom no celular.O jQuery.documentSize fornece $.windowWidth()e $.windowHeight(), que resolve esses problemas. Para mais informações, consulte a documentação .
Eu escrevi um pequeno bookmarklet javascript que você pode usar para exibir o tamanho. Você pode adicioná-lo facilmente ao seu navegador e sempre que clicar nele, verá o tamanho no canto direito da janela do navegador.
Aqui você encontra informações sobre como usar um bookmarklet https://en.wikipedia.org/wiki/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);
O código original está no café:
(->
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()
)()
Basicamente, o código está anexando uma pequena div que é atualizada quando você redimensiona sua janela.
Em alguns casos, relacionados ao layout responsivo, $(document).height()podem retornar dados incorretos que exibem apenas a altura da porta de exibição. Por exemplo, quando algum wrapper div # tem height: 100%, esse #wrapper pode ser esticado por algum bloco dentro dele. Mas sua altura ainda será como a altura da janela de exibição. Em tal situação, você pode usar
$('#wrapper').get(0).scrollHeight
Isso representa o tamanho real do wrapper.
Guia completo relacionado aos tamanhos de tela
Javascript
Para altura:
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.)
Nota: Quando a janela é maximizada, será igual a tela.
Para largura:
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
Para altura:
$(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.
Para largura:
$(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)
Eu desenvolvi uma biblioteca para saber o tamanho real da janela de visualização para navegadores de desktops e celulares, porque o tamanho da janela de visualização é inconsistente entre os dispositivos e não pode contar com todas as respostas dessa publicação (de acordo com todas as pesquisas que fiz sobre isso): https: // github .com / pyrsmk / W
Às vezes, você precisa ver as alterações de largura / altura enquanto redimensiona a janela e o conteúdo interno.
Para isso, escrevi um pequeno script que adiciona uma caixa de log que monitora dinamicamente todo o redimensionamento e atualizações quase que imediatas.
Ele adiciona um HTML válido com posição fixa e alto índice z, mas é pequeno o suficiente, portanto você possa :
Testado em: Chrome 40, IE11, mas é altamente possível trabalhar em outros navegadores mais antigos também ... :)
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 );
EDIT: Agora os estilos são aplicados apenas ao elemento da tabela de logger - não a todas as tabelas - também é uma solução sem jQuery :)
Com a introdução de globalThisno ES2020 você pode usar imóveis como.
Para tamanho da tela:
globalThis.screen.availWidth
globalThis.screen.availHeight
Para tamanho da janela
globalThis.outerWidth
globalThis.outerHeight
Para deslocamento:
globalThis.pageXOffset
globalThis.pageYOffset
...& em breve.
alert("Screen Width: "+ globalThis.screen.availWidth +"\nScreen Height: "+ globalThis.screen.availHeight)
Você pode usar a tela objeto para obter isso.
A seguir, é apresentado um exemplo do que retornaria:
Screen {
availWidth: 1920,
availHeight: 1040,
width: 1920,
height: 1080,
colorDepth: 24,
pixelDepth: 24,
top: 414,
left: 1920,
availTop: 414,
availLeft: 1920
}
Para obter sua screenWidthvariável, basta usar screen.width, mesmo com screenHeight, você usariascreen.height .
Para obter a largura e altura da janela, seria screen.availWidthouscreen.availHeight respectivamente.
Para as variáveis pageXe pageY, use window.screenX or Y. Observe que isso é da tela MUITO ESQUERDA / SUPERIOR DA TELA ESQUERDA / SUPERIOR . Portanto, se você tiver duas telas de largura 1920, uma janela de 500px à esquerda da tela direita teria um valor X de 2420(1920 + 500).screen.width/height, no entanto, exiba a largura ou a altura da tela ATUAL.
Para obter a largura e a altura da sua página, use jQuery $(window).height()ou$(window).width() .
Novamente usando jQuery, uso $("html").offset().tope $("html").offset().leftpara os seus pageXe pageYvalores.
// 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();
})();
Foi assim que consegui obter a largura da tela no projeto React JS:
Se a largura for igual a 1680, retorne 570 e retorne 200
var screenWidth = window.screen.availWidth;
<Label style={{ width: screenWidth == "1680" ? 570 : 200, color: "transparent" }}>a </Label>