Javascript 如何在iOS上使用Phonegap正确检测方向变化?

Javascript 如何在iOS上使用Phonegap正确检测方向变化?,javascript,iphone,ios,cordova,jqtouch,Javascript,Iphone,Ios,Cordova,Jqtouch,我在下面找到了这个定向测试代码,寻找JQTouch参考资料。这在MobileSafari上的iOS模拟器中正常工作,但在Phonegap中无法正确处理。我的项目遇到了与终止此测试页相同的问题。有没有办法在Phonegap中使用JavaScript来感知方向的变化 window.onorientationchange = function() { /*window.orientation returns a value that indicates whether iPhone is in p

我在下面找到了这个定向测试代码,寻找JQTouch参考资料。这在MobileSafari上的iOS模拟器中正常工作,但在Phonegap中无法正确处理。我的项目遇到了与终止此测试页相同的问题。有没有办法在Phonegap中使用JavaScript来感知方向的变化

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

我对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;
    }
}
你可能会在搜索PhoneGap Google组时遇到一些运气

我读到的一个关于如何检测方向的例子是Pie Guy:(,)。这与你发布的代码相似,但像你一样。。。我无法让它工作

有一个警告:eventListener对我有效,但我不确定这是否是一种过度密集的方法。到目前为止,这是唯一对我有效的方法,但我不知道是否有更好、更精简的方法



更新修复了上面的代码,现在可以使用了

我正在为iPhone的PhoneGap中创建一个jQTouch应用程序。我已经为这个问题争论了好几天了。我已经多次看到eventlistener解决方案的建议,但就是无法让它发挥作用

最后我想出了一个不同的解决办法。它基本上使用settimeout定期检查主体的宽度。如果宽度为320,则方向为纵向,如果为480,则为横向。然后,如果方向自上次检查以来发生了更改,它将启动纵向填充函数或横向填充函数,您可以在其中为每个方向执行操作

代码(注意,我知道代码中有一些重复,只是还没来得及删减!)


我使用
window.onresize=function(){checkOrientation();}
在checkOrientation中,您可以使用window.orientation或body width检查 但想法是,“window.onresize”是最跨浏览器的方法,至少在我有机会测试的大多数移动和桌面浏览器中是如此。

我就是这么做的:

函数doOnOrientationChange(){
开关(窗口方向){
案例-90:案例90:
警报(“景观”);
打破
违约:
警惕(“肖像”);
打破
}
}
window.addEventListener('orientationchange',doOnOrientationChange);
//如果需要,初始执行

doOnOrientationChange()以下内容对我有用:

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
的值不会立即更新

在处理
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)
  });
}

我发现这段代码可以检测设备是否处于横向,在本例中,添加了一个启动页面,上面写着“更改方向以查看站点”。它在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>

(功能(){
"严格使用",;
var isMobile={
Android:function(){
返回navigator.userAgent.match(/Android/i);
},
黑莓:函数(){
返回navigator.userAgent.match(/BlackBerry/i);
},
iOS:function(){
返回navigator.userAgent.match(/iPhone | iPad | iPod/i);
},
Opera:函数(){
返回navigator.userAgent.match(/Opera-Mini/i);
},
Windows:function(){
返回navigator.userAgent.match(/IEMobile/i);
},
any:function(){
返回(isMobile.Android()| | isMobile.BlackBerry()| | isMobile.iOS()| | isMobile.Opera()| | isMobile.Windows());
}
};
if(isMobile.any()){
doOnOrientationChange();
addEventListener('resize',doOnOrientationChange',false');
}
函数doOnOrientationChange(){
var a=document.getElementById('alert');
var b=document.body;
var w=b.偏移网络宽度;
var h=b.离地远视;
(w/h>1)?(a.className='show',b.className='full body'):(a.className='hide',b.className='';
}
})();
HTML:
本网站不被认为是以横向模式浏览的,请打开您的设备

以下是我所做的:

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
在触发
“orientationchange”
(至少在iOS上的Chrome中)后的几毫秒内未定义

我发现处理此问题的最佳方法是:

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);
我正在检查方向是否未定义,或者方向是否等于检测到的最后一个方向。如果其中一个为真,我等待10毫秒,然后再次解析方向。如果方向是正确的值,我将调用
showXOrientation
函数。如果方向无效,我将继续循环检查函数,每次等待10毫秒,直到它有效

现在,我会像往常一样为此制作一个JSFIDLE,但JSFIDLE并没有为我和我的支持工作
window.addEventListener('orientationchange', doOnOrientationChange);

function doOnOrientationChange()
{
      if (screen.height > screen.width) {
         console.log('portrait');
      } else {
         console.log('landscape');
      }
}
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);
if (window.DeviceOrientationEvent) {
    // Listen for orientation changes
    window.addEventListener("orientationchange", orientationChangeHandler);
    function orientationChangeHandler(evt) {
        // Announce the new orientation number
        // alert(screen.orientation);
        // Find matches
        var mql = window.matchMedia("(orientation: portrait)");

        if (mql.matches)  //true
    }
}