Búsqueda de sitios web

javascript - ¿Cómo detecto correctamente el cambio de orientación usando Phonegap en iOS?


Encontré el código de este test de orientación a continuación mientras buscaba material de referencia de JQTouch. Esto funciona correctamente en el simulador de iOS en Safari móvil, pero no se maneja correctamente en Phonegap. Mi proyecto se está encontrando con el mismo problema que está afectando a esta página de prueba. ¿Hay alguna manera de detectar el cambio de orientación usando JavaScript en Phonegap?

window.onorientationchange = function() {
  /*window.orientation returns a value that indicates whether iPhone is in portrait mode, landscape mode with the screen turned to the
    left, or landscape mode with the screen turned to the right. */
  var orientation = window.orientation;
  switch (orientation) {
    case 0:
      /* If in portrait mode, sets the body's class attribute to portrait. Consequently, all style definitions matching the body[class="portrait"] declaration
         in the iPhoneOrientation.css file will be selected and used to style "Handling iPhone or iPod touch Orientation Events". */
      document.body.setAttribute("class", "portrait");

      /* Add a descriptive message on "Handling iPhone or iPod touch Orientation Events"  */
      document.getElementById("currentOrientation").innerHTML = "Now in portrait orientation (Home button on the bottom).";
      break;

    case 90:
      /* If in landscape mode with the screen turned to the left, sets the body's class attribute to landscapeLeft. In this case, all style definitions matching the
         body[class="landscapeLeft"] declaration in the iPhoneOrientation.css file will be selected and used to style "Handling iPhone or iPod touch Orientation Events". */
      document.body.setAttribute("class", "landscape");

      document.getElementById("currentOrientation").innerHTML = "Now in landscape orientation and turned to the left (Home button to the right).";
      break;

    case -90:
      /* If in landscape mode with the screen turned to the right, sets the body's class attribute to landscapeRight. Here, all style definitions matching the
         body[class="landscapeRight"] declaration in the iPhoneOrientation.css file will be selected and used to style "Handling iPhone or iPod touch Orientation Events". */
      document.body.setAttribute("class", "landscape");

      document.getElementById("currentOrientation").innerHTML = "Now in landscape orientation and turned to the right (Home button to the left).";
      break;
  }
}

Respuesta #1

Esto es lo que hago:

function doOnOrientationChange() {
    switch(window.orientation) {  
      case -90: case 90:
        alert('landscape');
        break; 
      default:
        alert('portrait');
        break; 
    }
}
  
window.addEventListener('orientationchange', doOnOrientationChange);
  
// Initial execution if needed
doOnOrientationChange();

Actualización mayo 2019: window.orientation es una característica obsoleta y no es compatible con la mayoría de los navegadores según MDN. El evento orientationchange está asociado con window.orientation y, por lo tanto, probablemente no debería usarse.

Respuesta #2

Yo uso window.onresize=function(){ checkOrientation(); } Y en checkOrientation puedes emplear window.orientation o comprobar el ancho del body, pero la idea es que el "window.onresize" es el método más compatible entre navegadores, al menos con la mayoría de los navegadores móviles y de escritorio con los que he tenido oportunidad de probar.

Respuesta #3

if (window.matchMedia("(orientation: portrait)").matches) {
   // you're in PORTRAIT mode
}

if (window.matchMedia("(orientation: landscape)").matches) {
  // you're in LANDSCAPE mode
}

Respuesta #4

Soy bastante nuevo en iOS y Phonegap también, pero pude hacer esto agregando un eventListener. Hice lo mismo (usando el ejemplo que referencias), y no pude hacer que funcionara. Pero esto pareció resolverlo:

// Event listener to determine change (horizontal/portrait)
window.addEventListener("orientationchange", updateOrientation); 

function updateOrientation(e) {
switch (e.orientation)
{   
    case 0:
        // Do your thing
        break;

    case -90:
        // Do your thing
        break;

    case 90:
        // Do your thing
        break;

    default:
        break;
    }
}

Podrías tener algo de suerte buscando en el Grupo de Google de PhoneGap el término "orientation".

Un ejemplo que leí sobre cómo detectar la orientación fue Pie Guy: (juego, archivo js). Es similar al código que has publicado, pero como tú... no pude hacerlo funcionar.

Una advertencia: el eventListener funcionó para mí, pero no estoy seguro de si este es un enfoque demasiado intensivo. Hasta ahora ha sido la única forma que ha funcionado para mí, pero no sé si hay maneras mejores y más eficientes.

ACTUALIZACIÓN se corrigió el código de arriba, ahora funciona

Respuesta #5

Aunque la pregunta se refiere solo al uso de PhoneGap y iOS, y aunque ya fue respondida, puedo agregar algunos puntos a la pregunta más amplia de cómo detectar la orientación de la pantalla con JS en 2019:

  1. La propiedad window.orientation está obsoleta y no es compatible con los navegadores de Android. Existe una propiedad más reciente que proporciona más información sobre la orientación: screen.orientation. Pero todavía es experimental y no es compatible con iOS Safari. Por lo tanto, para lograr el mejor resultado probablemente necesites usar la combinación de ambas: const angle=screen.orientation ? screen.orientation.angle : window.orientation.

  2. Como @benallansmith mencionó en su comentario, el evento window.onorientationchange se dispara antes que window.onresize, por lo que no obtendrás las dimensiones reales de la pantalla a menos que agregues un pequeño retraso después del evento orientationchange.

  3. Existe un complemento de orientación de pantalla de Cordova para soportar navegadores móviles antiguos, pero creo que no hay necesidad de usarlo hoy en día.

  4. También había un evento screen.onorientationchange, pero está obsoleto y no se debe usar. Se añadió solo para completar la respuesta.

En mi caso de uso, no me importaba mucho la orientación real, sino más bien el ancho y alto real de la ventana, que obviamente cambia con la orientación. Así que usé el evento resize para evitar lidiar con los retrasos entre el evento orientationchange y la actualización de las dimensiones de la ventana:

window.addEventListener('resize', () => {
  console.log(`Actual dimensions: ${window.innerWidth}x${window.innerHeight}`);
  console.log(`Actual orientation: ${screen.orientation ? screen.orientation.angle : window.orientation}`);
});

Nota 1: Usé la sintaxis de EcmaScript 6 aquí, asegúrate de compilarla a ES5 si es necesario.

Nota 2: el evento window.onresize también se dispara cuando se activa el teclado virtual, no solo cuando cambia la orientación.

Artículos relacionados