Javascript máximo altura de la vista tras la orientación cambiar Android y iOS

La meta:

Para encontrar la altura máxima de la ventana gráfica de un dispositivo, incluyendo el espacio de la address bar para que podamos cambiar dinámicamente el min-body y empujar nuestro contenido hacia arriba.

El problema:

Los navegadores móviles manejan los estados de orientación de manera diferente y actualizan las propiedades de DOM en el cambio de orientación de manera diferente.

Detectar la rotación del teléfono Android en el navegador con JavaScript

Con los teléfonos Android, screen.width o screen.height también se actualiza a medida que se gira el dispositivo.

 |==============================================================================| | Device | Events Fired | orientation | innerWidth | screen.width | |==============================================================================| | iPad 2 | resize | 0 | 1024 | 768 | | (to landscape) | orientationchange | 90 | 1024 | 768 | |----------------+-------------------+-------------+------------+--------------| | iPad 2 | resize | 90 | 768 | 768 | | (to portrait) | orientationchange | 0 | 768 | 768 | |----------------+-------------------+-------------+------------+--------------| | iPhone 4 | resize | 0 | 480 | 320 | | (to landscape) | orientationchange | 90 | 480 | 320 | |----------------+-------------------+-------------+------------+--------------| | iPhone 4 | resize | 90 | 320 | 320 | | (to portrait) | orientationchange | 0 | 320 | 320 | |----------------+-------------------+-------------+------------+--------------| | Droid phone | orientationchange | 90 | 320 | 320 | | (to landscape) | resize | 90 | 569 | 569 | |----------------+-------------------+-------------+------------+--------------| | Droid phone | orientationchange | 0 | 569 | 569 | | (to portrait) | resize | 0 | 320 | 320 | 

Debido a esto, está claro que para encontrar la altura máxima de la ventana no importa qué orientación, usar una única función para devolver la altura máxima de un dispositivo nunca será constante sobre una gama de dispositivos.

Otros problemas que he descubierto que no hacen que estos dos jueguen bien:

  • La propiedad window.devicePixelRatio puede devolver alturas inconsistentes al dividir por window.outerHeight .
  • Delay window.setTimeout(function() {}, time) necesita ser usado para dar a los elementos DOM la oportunidad de actualizar después del cambio de orientación.
  • window.outerHeight no se actualiza en los cambios de orientación de los dispositivos iOS. El uso de screen.availHeight como screen.availHeight incluye la barra de navegación inferior como altura total.
  • Utilizar una #header , #content , #footer obliga a volver a calcular dinámicamente el #content{min-height} para empujar el #footer hacia abajo cuando el body se actualiza dyamically.

Una solución:

Primero echemos un vistazo a la estructura DIV:

 <style> #header,#content,#footer{width:100%;} </style> <body> <div id="header"></div> <div id="content"></div> <div id="footer"></div> </body> 

Queremos evitar que los dispositivos escalen por su cuenta:

 <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" /> 

Necesitamos ayuda para tener la capacidad de devolver una altura de vista máxima y ocultar la barra de direcciones para iOS:

 <script src="iOS.js" type="text/javascript"></script> 

Http://iosjs.com/

A continuación, detecte si el dispositivo admite el cambio de orientación y utiliza el cambio de tamaño como una alternativa:

 var iOS = (navigator.userAgent.match(/(iPad|iPhone|iPod)/i) ? true : false); var android = (navigator.userAgent.match(/Android/i) ? true : false); var supportsOrientationChange = "onorientationchange" in window; var orientationEvent = supportsOrientationChange ? "orientationchange" : "resize"; 

El vientre de la bestia:

 function updateOrientation() { var orientation = (window.orientation); if(android) { window.setTimeout(function() { window.scrollTo(0,0); var size = window.outerHeight/window.devicePixelRatio; $('body').css('min-height', size + 'px'); var headerHeight = $('#header').height(); var footerHeight = $('#footer').height(); var contentHeight = size - (headerHeight+footerHeight); $('#content').css('min-height', contentHeight + 'px'); window.scrollTo(0,1); }, 200); } if(iOS) { window.setTimeout(function(){ window.scrollTo(0,0); var size = iOS_getViewportSize(); var headerHeight = $('#header').height(); var footerHeight = $('#footer').height(); var contentHeight = size.height - (headerHeight+footerHeight); $('#content').css('min-height', contentHeight + 'px'); window.scrollTo(0,1); }, 0); } } 

Añada oyentes de eventos para el evento de carga y orientación de página:

 if(iOS) { iOS_addEventListener(window, "load", iOS_handleWindowLoad); iOS_addEventListener(window, "orientationchange", iOS_handleOrientationChange); iOS_addEventListener(window, "resize", iOS_handleReize); } addEventListener("load", function() { updateOrientation(); }, false); addEventListener(orientationEvent, function() { updateOrientation(); }, false); 

La prueba está en el budín:

IPhone 4 y 4s Retrato y paisaje

IPhone 4 y 4s RetratoPaisaje del iPhone 4 y 4s


Retrato y paisaje de Android

Retrato de AndroidAndroid Landscape


El objetivo aquí es minimizar esta solución o mejorarla.

Esta es una solución simple que agregará el ancho y la altura de los navegadores al cuerpo del documento en la carga y el cambio de tamaño de la ventana.

 jQuery.event.add(window, "load", resize); jQuery.event.add(window, "resize", resize); function resize() { var h = jQuery(window).height(); var w = jQuery(window).width(); jQuery("body").css({"width": w, "height": h}); } 

Valores esperados devueltos en el simulador de iOS. No puedo probar para Android en este momento.

 var supportsOrientationChange = "onorientationchange" in window; var orientationEvent = supportsOrientationChange ? "orientationchange" : "resize"; window.onload = updateOrientation(); window.addEventListener(orientationEvent, function() { updateOrientation(); }, false); function updateOrientation(){ switch(window.orientation){ case 0: alert(window.outerHeight); // Returns '356' with browser chrome break; case -90: alert('Landscape right'); break; case 90: alert(window.outerHeight); // Returns '208' w browser chrome break; case 180: //alert('Portrait view - upside down'); break; } var orientation = (window.orientation); } 

(Nota: Este código no se probará en un navegador.)

Usted podría intentar un cierre de auto-invocación que monitorea el cambio en la orientación por sí mismo. Algo como esto:

 (function () { var CurrentHeight; (function CheckForOrientationChange() { //var NewHeight = window.screen.availHeight / window.devicePixelRatio; //var NewHeight = $(window).height(); var NewHeight = $('#WidthCheck').width(); if (CurrentHeight && CurrentHeight!== NewHeight ) { alert(NewHeight); // change here } CurrentHeight = NewHeight; setTimeout(CheckForOrientationChange, 1000); })(); })(); 

Simplemente colóquelo en la función de preparación de documentos. Por ahora se comprueba cada segundo, pero se puede acortar ese intervalo. El jsfiddle está aquí y puedes probarlo cambiando el tamaño del navegador para simular el cambio de un navegador móvil y luego puedes adaptar el código para manejar tu acción.

  • Cómo ejecutar cordova plugin en el servicio de fondo de Android?
  • ¿Cómo interactuar con el menú USSD?
  • Chrome en Android no respeta el índice z para los clics de enlace
  • ¿Los dispositivos móviles tienen CPU suficiente para admitir HTTPS para todo el tráfico de un sitio web?
  • Cómo configurar el color de fondo de un elemento específico en listview por posición?
  • Bluetooth - Dispositivos de clase 1?
  • ¿Qué es APPKEY en Truecaller API?
  • Enlace externo y el botón de hardware atrás con jQuery Mobile
  • ¿Utiliza simultáneamente wifi y la interfaz 3G en Android?
  • ¿Cómo generar enlace waze meetup con fallback web?
  • ¿Qué idiomas de programación puedo utilizar para realizar aplicaciones para el sistema operativo Android Mobile?
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.