Как правильно определить изменение ориентации с помощью Phonegap на iOS?



Я нашел этот код теста ориентации ниже, ища справочный материал 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;
}
}
675   10  

10 ответов:

вот что я делаю:

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

Я использую window.onresize = function(){ checkOrientation(); } И в checkOrientation вы можете использовать окно.проверка ориентации или ширины тела но идея в том, что " окно.onresize " - это самый кросс-браузерный метод, по крайней мере, с большинством мобильных и настольных браузеров, с которыми у меня была возможность протестировать.

Я довольно новичок в iOS и Phonegap, но я смог сделать это, добавив в eventListener. Я сделал то же самое (используя пример, на который вы ссылаетесь), и не смог заставить его работать. Но это, казалось, делало свое дело:

// 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;
    }
}

возможно, Вам повезет с поиском группы Google PhoneGap термин "ориентация".

один пример, о котором я читал в качестве примера о том, как определить ориентацию, был Pie Guy: ( - игры,js файл). Это похоже на код, который вы опубликовали,но как вы... Я не мог заставить его работать.

одно предостережение: eventListener работал для меня, но я не уверен, что это слишком интенсивный подход. До сих пор это был единственный способ, который работал для меня, но я не знаю, есть ли лучшие, более обтекаемые способы.


обновление исправлен код выше, он работает сейчас

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

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

период работы с orientationchange событие, мне понадобился тайм-аут, чтобы получить правильные размеры элементов на странице, но matchMedia работал нормально. Мой последний код:

var matchMedia = window.msMatchMedia || window.MozMatchMedia || window.WebkitMatchMedia || window.matchMedia;

if (typeof(matchMedia) !== 'undefined') {
  // use matchMedia function to detect orientationchange
  window.matchMedia('(orientation: portrait)').addListener(function() {
    // your code ...
  });
} else {
  // use orientationchange event with timeout (fires to early)
  $(window).on('orientationchange', function() {
    window.setTimeout(function() {
      // your code ...
    }, 300)
  });
}

вот что я сделал:

window.addEventListener('orientationchange', doOnOrientationChange);

function doOnOrientationChange()
{
      if (screen.height > screen.width) {
         console.log('portrait');
      } else {
         console.log('landscape');
      }
}

Я считаю, что правильный ответ уже был опубликован и принят, но есть проблема, которую я испытал сам и что некоторые другие упоминали здесь.

на некоторых платформах, различные свойства, такие как размер окна (window.innerWidth,window.innerHeight) и window.orientation свойство не будет обновляться к тому времени, когда событие "orientationchange" был уволен. Много раз, свойство window.orientation - это undefined в течение нескольких миллисекунд после обстрела "orientationchange" (по крайней мере в Chrome на iOS).

лучший способ, который я нашел, чтобы справиться с этой проблемой было:

var handleOrientationChange = (function() {
    var struct = function(){
        struct.parse();
    };
    struct.showPortraitView = function(){
        alert("Portrait Orientation: " + window.orientation);
    };
    struct.showLandscapeView = function(){
        alert("Landscape Orientation: " + window.orientation);
    };
    struct.parse = function(){
        switch(window.orientation){
            case 0:
                    //Portrait Orientation
                    this.showPortraitView();
                break;
            default:
                    //Landscape Orientation
                    if(!parseInt(window.orientation) 
                    || window.orientation === this.lastOrientation)
                        setTimeout(this, 10);
                    else
                    {
                        this.lastOrientation = window.orientation;
                        this.showLandscapeView();
                    }
                break;
        }
    };
    struct.lastOrientation = window.orientation;
    return struct;
})();
window.addEventListener("orientationchange", handleOrientationChange, false);

Я проверяю, является ли ориентация неопределенной или если ориентация равна последней обнаруженной ориентации. Если любой из них истинен, я жду десять миллисекунд, а затем снова анализирую ориентацию. Если ориентация является правильным значением, я называю showXOrientation функции. Если ориентация недопустима, я продолжаю цикл моей функции проверки, ожидая десять миллисекунд каждый раз, пока он не будет действителен.

теперь я бы сделал JSFiddle для этого, как я обычно делал, но JSFiddle не работает для меня, и моя ошибка поддержки для него была закрыта, поскольку никто больше не сообщает о той же проблеме. Если кто-то хочет превратить это в JSFiddle, пожалуйста.

спасибо! Надеюсь, это поможет!

Я нашел этот код, чтобы определить, находится ли устройство в альбомной ориентации, и в этом случае добавьте заставку с надписью "изменить ориентацию, чтобы увидеть сайт". Он работает на iOS, Android и Windows телефонов. Я думаю, что это очень полезно, Так как это довольно элегантно и избежать, чтобы установить ландшафтный вид для мобильного сайта. Код работает очень хорошо. Единственное, что не полностью удовлетворяет, это то, что если кто-то загружает страницу, находящуюся в альбомном режиме, страница заставки не делает кажется.

<script>
(function() {
    'use strict';

    var isMobile = {
        Android: function() {
            return navigator.userAgent.match(/Android/i);
        },
        BlackBerry: function() {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        iOS: function() {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i);
        },
        Opera: function() {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        Windows: function() {
            return navigator.userAgent.match(/IEMobile/i);
        },
        any: function() {
            return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
        }
    };
    if (isMobile.any()) {
        doOnOrientationChange();
        window.addEventListener('resize', doOnOrientationChange, 'false');
    }

    function doOnOrientationChange() {
        var a = document.getElementById('alert');
        var b = document.body;
        var w = b.offsetWidth;
        var h = b.offsetHeight;
        (w / h > 1) ? (a.className = 'show', b.className = 'full-body') : (a.className = 'hide', b.className = '');
    }
})();
</script>

и HTML:<div id="alert" class="hide"> <div id="content">This site is not thought to be viewed in landscape mode, please turn your device </div> </div>

для меня сработало следующее:

function changeOrientation(){
switch(window.orientation) {
case 0: // portrait, home bottom
case 180: // portrait, home top
 alert("portrait H: "+$(window).height()+" W: "+$(window).width());       
 break;
          case -90: // landscape, home left
          case 90: // landscape, home right
        alert("landscape H: "+$(window).height()+" W: "+$(window).width());
            break;
        }
    }

 window.onorientationchange = function() { 
            //Need at least 800 milliseconds
            setTimeout(changeOrientation, 1000);
        }

мне нужен тайм-аут, потому что значение window.orientation не обновляется сразу

Я создаю приложение 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!');
}

Comments

    Ничего не найдено.