【问题标题】:Detect change in orientation using javascript使用javascript检测方向变化
【发布时间】:2021-04-06 20:51:14
【问题描述】:

是否可以使用 javascript 检测 iPad 或 Galaxy Tab 上浏览器方向的变化?我认为可以使用 css 媒体查询。

【问题讨论】:

    标签: javascript css ipad accelerometer galaxy-tab


    【解决方案1】:

    截至 2021 年

    应该这样做,

    let theDeviceIsRotated;
    function handlePortraitOrLandscape() {
      setTimeout(afterAnUnnoticableDelay,100); // This solves the wrong-firing-order issue on Samsung Browser.
      function afterAnUnnoticableDelay() {
        if (screen.orientation) { // Mainly for Android (as of 2021)
          // document.getElementById('or7on').innerHTML = screen.orientation.angle; // Returns 0 or 90 or 270 or 180 // Create a div with ID: "or7on" and uncomment to test
          if (screen.orientation.angle == 0)   {    theDeviceIsRotated="no";     }
          if (screen.orientation.angle == 90)  {    theDeviceIsRotated="toTheLeft";     }
          if (screen.orientation.angle == 270) {    theDeviceIsRotated="toTheRight";     }
          if (screen.orientation.angle == 180) {    theDeviceIsRotated="upsideDown";     }
        } else { // Mainly for iOS (as of 2021)
          // document.getElementById('or7on').innerHTML = window.orientation; // Returns 0 or 90 or -90 or 180 // Create a div with ID: "or7on" and uncomment to test
          if (window.orientation == 0)   {    theDeviceIsRotated="no";     }
          if (window.orientation == 90)  {    theDeviceIsRotated="toTheLeft";     }
          if (window.orientation == -90) {    theDeviceIsRotated="toTheRight";     }
          if (window.orientation == 180) {    theDeviceIsRotated="upsideDown";     }
        }
      }
    }
    handlePortraitOrLandscape(); // Set for the first time
    window.addEventListener("resize",handlePortraitOrLandscape); // Update when change happens
    

    【讨论】:

      【解决方案2】:

      你可以像这样使用orientationchange事件:

      window.addEventListener('orientationchange', function(event) {
           /* update layout per new orientation */
      });
      

      【讨论】:

        【解决方案3】:

        我意识到在这个线程中没有人提到当设备被倒置时会发生什么。 window.orientation 在水平放置时返回 -90 或 90。垂直保持时返回 0 或 180。有些设备支持,有些不支持倒置。我推荐,

        window.addEventListener("orientationchange", function() {
          
          if ( window.orientation == 0 || window.orientation == 180) {
            // WHEN IN PORTRAIT MODE
            
          } else {
            // WHEN IN LANDSCAPE MODE
            
          }
        }, false);
        

        另请注意,window.orientation 在桌面上返回 undefined

        【讨论】:

        • 至于 window.orientation 的弃用,目前尚不清楚浏览器是否真的会停止识别它。您必须同时关注 Android 和 iOS 方面。
        【解决方案4】:

        更新:

        你可能想看看

        jQuery mobile orientationchange

        或普通的 JS 之一:

        window.addEventListener("orientationchange", function() {
          alert(window.orientation);
        }, false);
        

        MDN:

        window.addEventListener("orientationchange", function() {
            alert("the orientation of the device is now " + screen.orientation.angle);
        });
        

        旧答案

        http://www.nczonline.net/blog/2010/04/06/ipad-web-development-tips/

        iPad 上的 Safari 确实支持 window.orientation 属性,因此如有必要,您可以使用它来确定用户是处于水平模式还是垂直模式。提醒一下这个功能:

        window.orientation is 0 when being held vertically
        window.orientation is 90 when rotated 90 degrees to the left (horizontal)
        window.orientation is -90 when rotated 90 degrees to the right (horizontal)
        

        还有一个orientationchange事件,当设备旋转时会在window对象上触发。

        您还可以使用 CSS 媒体查询来确定 iPad 是处于垂直还是水平方向,例如:

        <link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css">
        <link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css">
        

        http://www.htmlgoodies.com/beyond/webmaster/toolbox/article.php/3889591/Detect-and-Set-the-iPhone--iPads-Viewport-Orientation-Using-JavaScript-CSS-and-Meta-Tags.htm

        <script type="text/javascript">
        var updateLayout = function() {
          if (window.innerWidth != currentWidth) {
            currentWidth = window.innerWidth;
            var orient = (currentWidth == 320) ? "profile" : "landscape";
            document.body.setAttribute("orient", orient);
            window.scrollTo(0, 1);
          }
        };
        
        iPhone.DomLoad(updateLayout);
        setInterval(updateLayout, 400);
        </script>
        

        【讨论】:

        • 似乎从iOS 4.0 开始UIWebView 版本不再支持Javascript window.orientation 属性,或者至少我经历过。因此,我发现通知 UIWebView 的内部 Javascript 有关方向更改的唯一方法是调用 [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"didRotateTo('%@')", orient]];其中 webView 是我的 UIWebView 和 orient 是当前设备方向的字符串表示。 didRotateTo 是一个 javascript 函数,它接受一个参数(方向为字符串)
        • Wrt 轮询,当设备的方向改变时会触发一个orientationchange 事件。
        • 这是否也适用于 Windows Surface 平板电脑?我看到给定的答案有些过时了,所以我想知道是否有人会碰巧知道。我尝试运行脚本,但似乎只有开发人员控制台(在 Chrome 中)注册了方向更改。
        • 这行得通吗? window.addEventListener("orientationchange", function() { console.log("the orientation of the device is now " + screen.orientation.angle); });
        • 我发现:已弃用。不适用于新网站,从这里developer.mozilla.org/en-US/docs/Web/API/Window/… May-b 这个答案应该更新。
        【解决方案5】:

        来自“Cross-device, cross-browser portrait-landscape detection

        这是关于确定移动设备是处于纵向还是横向模式;你不需要关心它的方向。如您所知,如果您将 iPad 倒置,则它处于纵向模式。

        $(window).bind("resize", function(){
            screenOrientation = ($(window).width() > $(window).height())? 90 : 0;
        });
        

        90 表示横向,0 表示纵向、跨浏览器、跨设备。

        window.onresize 事件随处可用,并且总是在正确的时间触发;永远不会太早,永远不会太晚。事实上,屏幕的大小也总是准确的。

        JavaScript 版本是这样的,如果我错了,请纠正我。

          function getScreenOrientation() {
            screenOrientation = window.outerWidth > window.outerHeight ? 90 : 0;
            console.log("screenOrientation = " + screenOrientation);
          }
          window.addEventListener("resize", function(event) {
            getScreenOrientation();
          });
          getScreenOrientation();
        

        【讨论】:

        • 当用户竖起手机,然后打开一个虚拟键盘,导致在小屏幕上宽度变得比高度大时,情况如何?用户仍然以相同的纵向方向握住手机,但您的方法可能会导致方向变化的误报结果。
        • @IlliaRatkevych 好点。然而,这可以通过检查双方是否自开始/自上次检查以来发生变化而轻松停止。
        • 对我来说,使用 jquery 事件在 android 和 iphone 上都有效。 api.jquerymobile.com/orientationchange
        【解决方案6】:

        一个易于使用的 sn-p :

        function doOnOrientationChange()
        {
            switch(window.orientation)
            { 
                case -90:
                case 90:
                  // alert('landscape');
                  $('#portrait').css({display:'none'});
                  $('#landscape').css({display:'block'});
        
                  break;
                default:
                  // alert('portrait');
                  $('#portrait').css({display:'block'});
                  $('#landscape').css({display:'none'});
                  break;
            }
        }
        
        window.addEventListener('orientationchange', doOnOrientationChange);
        
        // First launch
        doOnOrientationChange();
        

        【讨论】:

          【解决方案7】:

          您可以使用mediaMatch 来评估 CSS 媒体查询,例如

          window
              .matchMedia('(orientation: portrait)')
              .addListener(function (m) {
                  if (m.matches) {
                      // portrait
                  } else {
                      // landscape
                  }
              });
          

          CSS 媒体查询在 orientationchange 之前触发。如果您希望捕捉事件的结束(当轮换完成时),请参阅mobile viewport height after orientation change

          【讨论】:

            【解决方案8】:

            除了@mplungjan 答案之外,我发现使用 webkit “native”(我不知道如何称呼它)事件“deviceorientation”获得了更好的结果。

            Mozilla Developer network 中,他们很好地解释了如何在 webkit 和 Gecko 之间进行规范化,帮助我解决了这个问题。

            【讨论】:

              【解决方案9】:

              window.orientation 是您正在寻找的。还有一个 onOrientationChange 事件 适用于 android、iphone,而且我很确定适用于 ipad

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2016-12-18
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多