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

2022-08-30 01:47:57

我在下面找到了这个方向测试代码,寻找JQTouch参考资料。这在移动 Safari 上的 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;
  }
}

答案 1

这就是我所做的:

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();

2019年5月更新:根据MDN,这是一项已弃用的功能,大多数浏览器都不支持此功能。该事件与 window.orientation 相关联,因此可能不应使用。window.orientationorientationchange


答案 2

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