Как правильно определить изменение ориентации с помощью Phonegap на iOS? - PullRequest
173 голосов
/ 12 марта 2011

Я нашел этот код теста ориентации ниже в поисках справочного материала JQTouch. Это работает правильно в симуляторе iOS на мобильном Safari, но неправильно обрабатывается в Phonegap. Мой проект сталкивается с той же проблемой, которая убивает эту тестовую страницу. Есть ли способ почувствовать изменение ориентации с помощью JavaScript в 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;
  }
}

Ответы [ 11 ]

0 голосов
/ 16 июня 2011

Я создаю приложение jQTouch в PhoneGap для iPhone.Я боролся с этой проблемой в течение нескольких дней.Я видел предложенное решение Eventlistener несколько раз, но просто не смог заставить его работать.

В конце концов, я нашел другое решение.Он в основном проверяет ширину тела периодически, используя settimeout.Если ширина 320, то ориентация книжная, если 480, то альбомная.Затем, если ориентация изменилась со времени последней проверки, она запустит либо функцию портретного заполнения, либо функцию ландшафтного заполнения, где вы можете выполнять свои действия для каждой ориентации.

Код (обратите внимание, я знаю, что есть некоторыеповторение в коде, просто еще не удосужился урезать его!):

// get original orientation based on body width
deviceWidth = $('body').width();
if (deviceWidth == 320) {
    currentOrientation = "portrait";
}
else if (deviceWidth == 480) {
    currentOrientation = "landscape";
}

// fire a function that checks the orientation every x milliseconds
setInterval(checkOrientation, 500);

// check orientation
function checkOrientation() {
    deviceWidth = $('body').width();
    if (deviceWidth == '320') {
        newOrientation = "portrait";
    }
    else if (deviceWidth == '480') {
        newOrientation = "landscape";
    }
    // if orientation changed since last check, fire either the portrait or landscape function
    if (newOrientation != currentOrientation) {
        if (newOrientation == "portrait") {
            changedToPortrait();
        }
        else if (newOrientation == "landscape") {
            changedToLandscape();
        }
        currentOrientation = newOrientation;
    }
}

// landscape stuff
function changedToLandscape() {
    alert('Orientation has changed to Landscape!');
}

// portrait stuff
function changedToPortrait() {
    alert('Orientation has changed to Portrait!');
}
...