Prevent orientation change in iOS Safari

前端 未结 9 1562
死守一世寂寞
死守一世寂寞 2020-11-28 02:56

Is it possible to avoid transition to landscape view in Safari for iOS when the device is rotated?

iOS Safari has the \"orentationchange\" event, I tried to intercep

9条回答
  •  星月不相逢
    2020-11-28 03:40

    While you cannot prevent orientation change from taking effect you can emulate no change as stated in other answers.

    First detect device orientation or reorientation and, using JavaScript, add a class name to your wrapping element (in this example I use the body tag).

    function deviceOrientation() {
      var body = document.body;
      switch(window.orientation) {
        case 90:
          body.classList = '';
          body.classList.add('rotation90');
          break;
        case -90:
          body.classList = '';
          body.classList.add('rotation-90');
          break;
        default:
          body.classList = '';
          body.classList.add('portrait');
          break;
      }
    }
    window.addEventListener('orientationchange', deviceOrientation);
    deviceOrientation();
    

    Then if the device is landscape, use CSS to set the body width to the viewport height and the body height to the viewport width. And let’s set the transform origin while we’re at it.

    @media screen and (orientation: landscape) {
      body {
        width: 100vh;
        height: 100vw;
        transform-origin: 0 0;
      }
    }
    

    Now, reorient the body element and slide (translate) it into position.

    body.rotation-90 {
      transform: rotate(90deg) translateY(-100%);
    }
    body.rotation90 {
      transform: rotate(-90deg) translateX(-100%);
    }
    

提交回复
热议问题