检测视口方向,如果方向是纵向显示警告消息,建议用户说明

问题描述 投票:172回答:31

我正在建立专门针对移动设备的网站。特别是有一个页面,最好以横向模式查看。

有没有办法检测访问该页面的用户是否在纵向模式下查看它,如果是,则显示一条消息,通知用户该页面最好以横向模式查看?如果用户已在横向模式下查看,则不会显示任何消息。

所以基本上,我希望网站检测视口方向,如果方向是纵向,则显示警告消息,告知用户该页面在横向模式下最佳查看。

javascript jquery mobile viewport device-orientation
31个回答
245
投票
if(window.innerHeight > window.innerWidth){
    alert("Please use Landscape!");
}

jQuery Mobile有一个事件来处理这个属性的变化...如果你想警告以后有人转动 - orientationchange

此外,经过一些谷歌搜索,检查window.orientation(我相信以度数衡量......)


5
投票

我结合了两个解决方案,它对我来说很好。

window.addEventListener("orientationchange", function() {                   
    if (window.matchMedia("(orientation: portrait)").matches) {
       alert("PORTRAIT")
     }
    if (window.matchMedia("(orientation: landscape)").matches) {
      alert("LANSCAPE")
     }
}, false);

4
投票

通过获取方向(在您的js代码中的任何时间)

window.orientation

window.orientation返回0180然后你处于纵向模式,当返回90270然后你处于横向模式。


3
投票

我不同意最投票的答案。使用screen而不是window

    if(screen.innerHeight > screen.innerWidth){
    alert("Please use Landscape!");
}

是正确的方法吗?如果你用window.height计算,你将在Android上遇到麻烦。当键盘打开时,窗口会缩小。所以使用屏幕而不是窗口。

screen.orientation.type是一个很好的答案,但与IE。 https://caniuse.com/#search=screen.orientation


2
投票
//see also http://stackoverflow.com/questions/641857/javascript-window-resize-event
//see also http://mbccs.blogspot.com/2007/11/fixing-window-resize-event-in-ie.html
/*
Be wary of this:
While you can just hook up to the standard window resize event, you'll find that in IE, the event is fired once for every X and once for every Y axis movement, resulting in a ton of events being fired which might have a performance impact on your site if rendering is an intensive task.
*/

//setup 
window.onresize = function(event) {
    window_resize(event);
}

//timeout wrapper points with doResizeCode as callback
function window_resize(e) { 
     window.clearTimeout(resizeTimeoutId); 
     resizeTimeoutId = window.setTimeout('doResizeCode();', 10); 
}

//wrapper for height/width check
function doResizeCode() {
    if(window.innerHeight > window.innerWidth){
        alert("Please view in landscape");
    }
}

2
投票

根据宽度/高度的比较确定方向的另一种方法:

var mql = window.matchMedia("(min-aspect-ratio: 4/3)");
if (mql.matches) {
     orientation = 'landscape';
} 

你在“调整大小”事件中使用它:

window.addEventListener("resize", function() { ... });

2
投票

仅限CCS

@media (max-width: 1024px) and (orientation: portrait){ /* tablet and smaller */
  body:after{
    position: absolute;
    z-index: 9999;
    width: 100%;
    top: 0;
    bottom: 0;
    content: "";
    background: #212121 url(http://i.stack.imgur.com/sValK.png) 0 0 no-repeat; /* replace with an image that tells the visitor to rotate the device to landscape mode */
    background-size: 100% auto;
    opacity: 0.95;
  }
}

在某些情况下,您可能希望在访问者旋转设备后添加一小段代码重新加载到页面,以便正确呈现CSS:

window.onorientationchange = function() { 
    var orientation = window.orientation; 
        switch(orientation) { 
            case 0:
            case 90:
            case -90: window.location.reload(); 
            break; } 
};

2
投票

当方向改变时,iOS不会更新screen.widthscreen.height。 Android在更改时不会更新window.orientation

我对这个问题的解决方案:

var isAndroid = /(android)/i.test(navigator.userAgent);

if(isAndroid)
{
    if(screen.width < screen.height){
        //portrait mode on Android
    }
} else {
    if(window.orientation == 0){
        //portrait mode iOS and other devices
    }
}

您可以使用以下代码在Android和iOS上检测此方向的更改:

var supportsOrientationChange = "onorientationchange" in window,
    orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

window.addEventListener(orientationEvent, function() {
    alert("the orientation has changed");
}, false);

如果不支持onorientationchange事件,则事件绑定将是resize事件。


2
投票
$(window).on("orientationchange",function( event ){
    alert(screen.orientation.type)
});

1
投票

感谢tobyodavies指导方式。

要根据移动设备的方向获得警报消息,您需要在function setHeight() {中实现以下脚本

if(window.innerHeight > window.innerWidth){
    alert("Please view in landscape");
}

1
投票

而不是270,它可以是-90(减去90)。


133
投票

您也可以使用window.matchMedia,我使用和喜欢它,因为它非常类似于CSS语法:

if (window.matchMedia("(orientation: portrait)").matches) {
   // you're in PORTRAIT mode
}

if (window.matchMedia("(orientation: landscape)").matches) {
   // you're in LANDSCAPE mode
}

在iPad 2上测试过。


1
投票

这扩展了之前的答案。我发现的最佳解决方案是创建一个无害的CSS属性,只有在满足CSS3媒体查询时才出现,然后对该属性进行JS测试。

例如,在CSS中你有:

@media screen only and (orientation:landscape)
{
    //  Some innocuous rule here
    body
    {
        background-color: #fffffe;
    }
}
@media screen only and (orientation:portrait)
{
    //  Some innocuous rule here
    body
    {
        background-color: #fffeff;
    }
}

然后你去JavaScript(我使用jQuery进行测试)。颜色声明可能很奇怪,所以你可能想要使用别的东西,但这是我发现用于测试它的最简单的方法。然后,您可以使用resize事件来接收切换。全部放在一起:

function detectOrientation(){
    //  Referencing the CSS rules here.
    //  Change your attributes and values to match what you have set up.
    var bodyColor = $("body").css("background-color");
    if (bodyColor == "#fffffe") {
        return "landscape";
    } else
    if (bodyColor == "#fffeff") {
        return "portrait";
    }
}
$(document).ready(function(){
    var orientation = detectOrientation();
    alert("Your orientation is " + orientation + "!");
    $(document).resize(function(){
        orientation = detectOrientation();
        alert("Your orientation is " + orientation + "!");
    });
});

最好的部分是,在我写这个答案时,它似乎对桌面界面没有任何影响,因为它们(通常)不会(似乎)传递任何参数来定向页面。


1
投票

这是我找到的最好的方法,基于David Walsh的文章(Detect Orientation Change on Mobile Devices

if ( window.matchMedia("(orientation: portrait)").matches ) {  
   alert("Please use Landscape!") 
}

说明:

Window.matchMedia()是一种本机方法,允许您定义媒体查询规则并在任何时间点检查其有效性。

我发现在这个方法的返回值上附加一个onchange监听器很有用。例:

var mediaQueryRule = window.matchMedia("(orientation: portrait)")
mediaQueryRule.onchange = function(){ alert("screen orientation changed") }

1
投票

我用于Android Chrome "The Screen Orientation API"

要查看当前方向,请调用console.log(screen.orientation.type)(可能还有screen.orientation.angle)。

结果:portrait-primary |肖像中学| landscape-primary |景观二次

下面是我的代码,我希望它会有所帮助:

var m_isOrientation = ("orientation" in screen) && (typeof screen.orientation.lock == 'function') && (typeof screen.orientation.unlock == 'function');
...
if (!isFullscreen()) return;
screen.orientation.lock('landscape-secondary').then(
    function() {
        console.log('new orientation is landscape-secondary');
    },
    function(e) {
        console.error(e);
    }
);//here's Promise
...
screen.orientation.unlock();
  • 我只测试了Android Chrome - 好的

1
投票
screen.orientation.addEventListener("change", function(e) {
 console.log(screen.orientation.type + " " + screen.orientation.angle);
}, false);

1
投票

iOS设备上的JavaScript中的窗口对象具有一个orientation属性,可用于确定设备的旋转。以下显示了不同方向的iOS设备(例如iPhone,iPad,iPod)的值window.orientation。

此解决方案也适用于Android设备。我检查了Android原生浏览器(Internet浏览器)和Chrome浏览器,即使在旧版本中也是如此。

function readDeviceOrientation() {                      
    if (Math.abs(window.orientation) === 90) {
        // Landscape
    } else {
        // Portrait
    }
}

1
投票

这就是我使用的。

function getOrientation() {

    // if window.orientation is available...
    if( window.orientation && typeof window.orientation === 'number' ) {

        // ... and if the absolute value of orientation is 90...
        if( Math.abs( window.orientation ) == 90 ) {

              // ... then it's landscape
              return 'landscape';

        } else {

              // ... otherwise it's portrait
              return 'portrait';

        }

    } else {

        return false; // window.orientation not available

    }

}

履行

window.addEventListener("orientationchange", function() {

     // if orientation is landscape...
     if( getOrientation() === 'landscape' ) {

         // ...do your thing

    }

}, false);

1
投票

如果你有最新的浏览器window.orientation可能无法正常工作。在这种情况下,使用以下代码获取角度 -

var orientation = window.screen.orientation.angle;

这仍然是一项实验性技术,您可以检查浏览器兼容性here


0
投票
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title>Rotation Test</title>
  <link type="text/css" href="css/style.css" rel="stylesheet"></style>
  <script src="js/jquery-1.5.min.js" type="text/javascript"></script>
  <script type="text/javascript">
        window.addEventListener("resize", function() {
            // Get screen size (inner/outerWidth, inner/outerHeight)
            var height = $(window).height();
            var width = $(window).width();

            if(width>height) {
              // Landscape
              $("#mode").text("LANDSCAPE");
            } else {
              // Portrait
              $("#mode").text("PORTRAIT");
            }
        }, false);

  </script>
 </head>
 <body onorientationchange="updateOrientation();">
   <div id="mode">LANDSCAPE</div>
 </body>
</html>

0
投票

有一种方法可以检测用户是否使用screen.orientation将设备翻转为纵向模式

只需使用以下代码:

screen.orientation.onchange = function () {
     var type = screen.orientation.type;
     if (type.match(/portrait/)) {
         alert('Please flip to landscape, to use this app!');
     }
}

现在,onchange将在用户翻转设备时被解雇,当用户使用纵向模式时会弹出警报。


0
投票

有关window.orientation的一点需要注意的是,如果您不在移动设备上,它将返回undefined。所以检查方向的好功能可能看起来像这样,其中xwindow.orientation

//check for orientation
function getOrientation(x){
  if (x===undefined){
    return 'desktop'
  } else {
    var y;
    x < 0 ? y = 'landscape' : y = 'portrait';
    return y;
  }
}

这样称呼它:

var o = getOrientation(window.orientation);
window.addEventListener("orientationchange", function() {
  o = getOrientation(window.orientation);
  console.log(o);
}, false);

88
投票

大卫沃尔什有一个更好,更直接的方法。

// Listen for orientation changes
window.addEventListener("orientationchange", function() {
  // Announce the new orientation number
  alert(window.orientation);
}, false);

在这些更改期间,window.orientation属性可能会更改。值0表示纵向视图,-90表示设备横向旋转到右侧,90表示设备横向旋转到左侧。

http://davidwalsh.name/orientation-change


0
投票

或者你可以使用它..

window.addEventListener("orientationchange", function() {
    if (window.orientation == "90" || window.orientation == "-90") {
        //Do stuff
    }
}, false);

33
投票

你可以使用CSS3:

@media screen and (orientation:landscape)
{
   body
   {
      background: red;
   }
}

19
投票

有几种方法可以做到,例如:

  • 检查window.orientation
  • 比较innerHeightinnerWidth

您可以采用以下方法之一。


检查设备是否处于纵向模式

function isPortrait() {
    return window.innerHeight > window.innerWidth;
}

检查设备是否处于横向模式

function isLandscape() {
    return (window.orientation === 90 || window.orientation === -90);
}

用法示例

if (isPortrait()) {
    alert("This page is best viewed in landscape mode");
}

如何检测方向变化?

$(document).ready(function() {
    $(window).on('orientationchange', function(event) {
        console.log(orientation);
    });
});

10
投票

我认为更稳定的解决方案是使用屏幕而不是窗口,因为如果您要在台式计算机上调整浏览器窗口的大小,它可以是横向或纵向。

if (screen.height > screen.width){
    alert("Please use Landscape!");
}

8
投票

为了将所有这些伟大的注释应用到我的日常编码中,为了我所有应用程序之间的连续性,我决定在我的jquery和jquery移动代码中使用以下内容。

window.onresize = function (event) {
  applyOrientation();
}

function applyOrientation() {
  if (window.innerHeight > window.innerWidth) {
    alert("You are now in portrait");
  } else {
    alert("You are now in landscape");
  }
}

6
投票

不要尝试修复window.orientation查询(0,90等并不意味着肖像,风景等):

http://www.matthewgifford.com/blog/2011/12/22/a-misconception-about-window-orientation/

即使在iOS7上,取决于你如何进入浏览器0并不总是肖像


5
投票

经过一些实验,我发现旋转方向感知设备将始终触发浏览器窗口的resize事件。所以在你的resize处理程序中只需调用一个函数:

function is_landscape() {
  return (window.innerWidth > window.innerHeight);
}
© www.soinside.com 2019 - 2024. All rights reserved.