iPhone 웹 애플리케이션에서 오리엔테이션을 초상화 모드로 잠그려면 어떻게해야합니까?

StackOverflow https://stackoverflow.com/questions/1207008

  •  05-07-2019
  •  | 
  •  

문제

iPhone 웹 애플리케이션을 구축하고 있으며 오리엔테이션을 초상화 모드로 고정하고 싶습니다. 이게 가능해? 이 작업을 수행 할 웹 키트 확장이 있습니까?

이것은 Mobile Safari 용 HTML 및 JavaScript로 작성된 응용 프로그램입니다. Objective-C로 작성된 기본 응용 프로그램이 아닙니다.

도움이 되었습니까?

해결책

뷰포트 방향을 기반으로 CSS 스타일을 지정할 수 있습니다. BODY [Orient = "Landscape"] 또는 Body [Orient = "Portrait"]로 브라우저를 대상으로합니다.

http://www.evotech.net/blog/2007/07/web-development-for-the-iphone/

하지만...

이 문제에 대한 Apple의 접근 방식은 개발자가 방향 변경에 따라 CSS를 변경할 수는 있지만 완전히 방향을 방지하지 않도록하는 것입니다. 다른 곳에서 비슷한 질문을 찾았습니다.

http://ask.metafilter.com/99784/how-can-i-lock-iphone-orientation-in-mobile-safari

다른 팁

이것은 꽤 해킹 된 솔루션이지만 적어도 (?)입니다. 아이디어는 CSS 변환을 사용하여 페이지의 내용을 준 포 트레이트 모드로 회전시키는 것입니다. 다음은 JavaScript (jQuery로 표현 됨) 코드로 시작하여 시작합니다.

$(document).ready(function () {
  function reorient(e) {
    var portrait = (window.orientation % 180 == 0);
    $("body > div").css("-webkit-transform", !portrait ? "rotate(-90deg)" : "");
  }
  window.onorientationchange = reorient;
  window.setTimeout(reorient, 0);
});

코드는 페이지의 전체 내용이 신체 요소 바로 내부 DIV 내부에 살기를 기대합니다. 조경 모드에서 DIV 90도 회전 - 초상화로 돌아갑니다.

독자에게 연습으로 남겨진다 : div는 중심점 주위에서 회전하므로 완벽하게 정사각형이 아닌 한 위치를 조정해야 할 것입니다.

또한 매력적인 시각적 문제가 있습니다. 방향을 변경하면 Safari가 천천히 회전 한 다음 최상위 DIV가 90 도로 스냅됩니다. 더 재미있게 추가하십시오

body > div { -webkit-transition: all 1s ease-in-out; }

CSS에. 장치가 회전하면 Safari가 수행하면 페이지의 내용이 수행됩니다. 속이는!

이 답변은 아직 불가능하지만 "미래 세대"를 위해 게시하고 있습니다. 바라건대, 언젠가 우리는 css @viewport 규칙을 통해 이것을 할 수 있기를 바랍니다.

@viewport {
    orientation: portrait;
}

사양 (프로세스) :
https://drafts.csswg.org/css-device-adapt/#orientation-desc

MDN :
https://developer.mozilla.org/en-us/docs/web/css/@viewport/orientation

MDN 브라우저 호환성 테이블과 다음 기사를 기반으로 IE 및 Opera의 특정 버전에서 일부 지원이있는 것처럼 보입니다.
http://menacingcloud.com/?c=cssviewportormetatag

이 JS API 사양도 관련이 있습니다.
https://w3c.github.io/screen-orientation/

제안 된 것과 함께 가능했기 때문에 @viewport 규칙, 설정으로 가능할 것입니다 orientation 뷰포트 설정에서 meta 태그, 그러나 나는 지금까지 이것으로 성공하지 못했습니다.

상황이 향상됨에 따라이 답변을 자유롭게 업데이트하십시오.

다음 코드는 HTML5 게임에서 사용되었습니다.

$(document).ready(function () {
     $(window)    
          .bind('orientationchange', function(){
               if (window.orientation % 180 == 0){
                   $(document.body).css("-webkit-transform-origin", "")
                       .css("-webkit-transform", "");               
               } 
               else {                   
                   if ( window.orientation > 0) { //clockwise
                     $(document.body).css("-webkit-transform-origin", "200px 190px")
                       .css("-webkit-transform",  "rotate(-90deg)");  
                   }
                   else {
                     $(document.body).css("-webkit-transform-origin", "280px 190px")
                       .css("-webkit-transform",  "rotate(90deg)"); 
                   }
               }
           })
          .trigger('orientationchange'); 
});

미디어 쿼리를 사용하여 화면을 회전시키는이 CSS 전용 방법을 생각해 냈습니다. 쿼리는 화면 크기를 기반으로합니다 내가 여기서 찾은 것. 480px는 너비가 480px 이상 또는 480px 미만인 장치가 없기 때문에 좋은 것 같습니다.

@media (max-height: 480px) and (min-width: 480px) and (max-width: 600px) { 
    html{
        -webkit-transform: rotate(-90deg);
           -moz-transform: rotate(-90deg);
            -ms-transform: rotate(-90deg);
             -o-transform: rotate(-90deg);
                transform: rotate(-90deg);
        -webkit-transform-origin: left top;
           -moz-transform-origin: left top;
            -ms-transform-origin: left top;
             -o-transform-origin: left top;
                transform-origin: left top;
        width: 320px; /*this is the iPhone screen width.*/
        position: absolute;
        top: 100%;
            left: 0
    }
}

Screen.lockOrientation() 이 문제를 해결하지만 당시 지원은 보편적이지 않지만 (2017 년 4 월) :

https://www.w3.org/tr/screen-orientation/

https://developer.mozilla.org/en-us/docs/web/api/screen.lockorientation

나는 사용자에게 휴대 전화를 초상화 모드로 다시 넣도록 지시한다는 아이디어가 마음에 듭니다. 여기에 언급 된 것처럼 : http://tech.sarathdr.com/featured/prevent-landscape-orientation-of-iphone-web-apps/... 그러나 JavaScript 대신 CSS를 사용합니다.

어쩌면 새로운 미래에는 상자 밖의 솔루션이있을 것입니다 ...

2015 년 5 월,

그렇게하는 실험적 기능이 있습니다.

그러나 Firefox 18+, IE11+및 Chrome 38+에서만 작동합니다.

그러나 아직 오페라 나 사파리에서는 작동하지 않습니다.

https://developer.mozilla.org/en-us/docs/web/api/screen/lockorientation#browser_compatibility

호환 브라우저의 현재 코드는 다음과 같습니다.

var lockOrientation = screen.lockOrientation || screen.mozLockOrientation || screen.msLockOrientation;

lockOrientation("landscape-primary");
// CSS hack to prevent layout breaking in landscape
// e.g. screens larger than 320px  
html {
  width: 320px;
  overflow-x: hidden;
}

이것은 또는 유사한 CSS 솔루션이 당신이 추구하는 경우 적어도 레이아웃을 보존합니다.

루트 솔루션은 장치 기능을 제한하지 않고 장치의 기능을 설명합니다. 장치가 단순한 해킹보다 적절한 제한을 허용하지 않으면 설계가 본질적으로 불완전하기 때문에 최선의 방법입니다. 단순할수록 좋습니다.

누군가가 필요한 경우 커피로.

    $(window).bind 'orientationchange', ->
        if window.orientation % 180 == 0
            $(document.body).css
                "-webkit-transform-origin" : ''
                "-webkit-transform" : ''
        else
            if window.orientation > 0
                $(document.body).css
                    "-webkit-transform-origin" : "200px 190px"
                    "-webkit-transform" : "rotate(-90deg)"
            else
                $(document.body).css
                    "-webkit-transform-origin" : "280px 190px"
                    "-webkit-transform" : "rotate(90deg)"

오리엔테이션 변경이 적용되는 것을 방지 할 수는 없지만 다른 답변에 명시된대로 변경을 모방 할 수 없습니다.

먼저 장치 방향 또는 재배 향을 감지하고 JavaScript를 사용하여 랩핑 요소에 클래스 이름을 추가하십시오 (이 예에서는 본체 태그를 사용합니다).

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

그런 다음 장치가 조경 인 경우 CSS를 사용하여 신체 너비를 뷰포트 높이로 설정하고 차체 높이를 뷰포트 너비로 설정하십시오. 그리고 우리가 그에있는 동안 변환 원점을 설정합시다.

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

이제 신체 요소를 재활하고 미끄러지기 (번역)를 제 위치로 바꿉니다.

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

@grumdrig의 답변에서 영감을 얻었으며 중고 지침 중 일부가 작동하지 않기 때문에 다른 사람이 필요한 경우 다음 스크립트를 제안합니다.

    $(document).ready(function () {

      function reorient(e) {
        var orientation = window.screen.orientation.type;
        $("body > div").css("-webkit-transform", (orientation == 'landscape-primary' || orientation == 'landscape-secondary') ? "rotate(-90deg)" : "");
      }
    $(window).on("orientationchange",function(){
        reorient();
    });
      window.setTimeout(reorient, 0);
    });

딸깍 하는 소리 여기 내 웹 사이트에서 튜토리얼 및 작업 예제.

실제로 jQuery 모바일 화면 방향을 보이기 위해 해킹을 사용할 필요가 없으며 실제로 PhoneGap을 사용하지 않는 한 더 이상 PhoneGap을 사용해야합니다.

2015 년 에이 작업을 수행하려면 다음과 같습니다.

  • Cordova (4.0을 초과하는 모든 버전은 더 좋습니다)
  • PhoneGap (PhoneGap을 사용할 수도 있고 플러그인이 호환됩니다)

Cordova 버전에 따라이 플러그인 중 하나입니다.

  • net.yoik.cordova.plugins.screenorientation (Cordova <4)

Cordova 플러그인 추가 net.yoik.cordova.plugins.screenorientation

  • Cordova 플러그인 추가 Cordova-Plugin-Screen-Orientation (Cordova> = 4)

Cordova 플러그인을 추가하여 Cordova-Plugin-screen-니스 지향을 추가합니다

화면 방향을 잠그려면이 기능을 사용합니다.

screen.lockOrientation('landscape');

잠금을 해제하려면 :

screen.unlockOrientation();

가능한 오리엔테이션 :

  • 초상-프라이팬 방향은 기본 초상화 모드에 있습니다.

  • 초상화 방향은 보조 초상화 모드에 있습니다.

  • 조경-프라이팬 방향은 기본 조경 모드에 있습니다.

  • 조경 고등 방향은 2 차 조경 모드에 있습니다.

  • 초상화 방향은 인물 유사 또는 초상화 고등학교 (센서)입니다.

  • 풍경 방향은 조경 유사 또는 조경 과도 (센서)입니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top