2011-12-14 124 views
13

utilicé screen.width para obtener el ancho del navegador. funcionó bien con el safari de iphone, pero no funcionó en el teléfono Android (mostraba 800 de ancho para el navegador de Android).Javascript para detectar el ancho de la pantalla del navegador móvil?

¿Hay alguna forma compatible de obtener el ancho de la pantalla. No quiero usar UserAgent para verificar si su navegador móvil. Me gustaría utilizar un javascript para eso y la lógica debe incluir el ancho de la pantalla.

Respuesta

3

Usted puede tratar de esta URL para detect screen size and apply a CSS style

o

<script type="text/javascript"> 

    function getWidth() 
    { 
    xWidth = null; 
    if(window.screen != null) 
     xWidth = window.screen.availWidth; 

    if(window.innerWidth != null) 
     xWidth = window.innerWidth; 

    if(document.body != null) 
     xWidth = document.body.clientWidth; 

    return xWidth; 
    } 
function getHeight() { 
    xHeight = null; 
    if(window.screen != null) 
    xHeight = window.screen.availHeight; 

    if(window.innerHeight != null) 
    xHeight = window.innerHeight; 

    if(document.body != null) 
    xHeight = document.body.clientHeight; 

    return xHeight; 
} 

</script> 


screen.height   shows the height of the screen 
screen.width   shows the width of the screen 
screen.availHeight shows height but removes the interface height like taskbar, and browser menu etc. 
screen.availWidth same as above,instead gives available width 
4

Se sabe tema - ver here

Cuando la página se carga por primera y la screen.widthscreen.height están equivocados. Pruebe con un tiempo de espera de la siguiente manera:

setTimeout(CheckResolution, 300); 

Dónde CheckResolution es su función.

0

Me parece que el uso de window.outerWidth da el valor correcto. Probado esto usando emuladores de Android BrowserStack.

+0

Esto sólo devuelve el ancho de la ventana completa incluyendo el cromo y todo. – malthoff

1

Para aquellos interesados ​​en obtener los valores de anchura del navegador, he probado varias opciones:

estoy usando arranque 3 y la única solución que coincide con el arranque de 3 puntos de corte con IE y Chrome fue:

window.innerWidth 

Estos son los resultados con 1200px ventana con:

Chrome

$(window).width(): 1183 
$(document).width():1183 
screen.width: 1536 
$(window).innerWidth():1183 
$(document).innerWidth():1183 
window.innerWidth: 1200 
$(document).outerWidth():1183 
window.outerWidth: 1216 
document.documentElement.clientWidth: 1183 

Internet Explorer 10

$(window).width(): 1200 
$(document).width():1200 
screen.width: 1536 
$(window).innerWidth():1200 
$(document).innerWidth():1200 
window.innerWidth: 1200 
$(document).outerWidth():1200 
window.outerWidth: 1214 
document.documentElement.clientWidth: 1200 
Cuestiones relacionadas