我正在为移动设备建立一个网站。有一页特别适合在横屏模式下浏览。

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

所以基本上,我想让网站检测视口的方向,如果方向是纵向,然后显示一个警告消息,建议用户这个页面最好在横向模式下查看。


当前回答

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

其他回答

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

获得方向(在任何时间在你的js代码)通过

window.orientation

当窗口。方向返回0或180则处于竖屏模式,返回90或270则处于横屏模式。

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

jQuery Mobile有一个事件来处理这个属性的变化…如果你想警告如果有人旋转后-定向变化

另外,在谷歌搜索之后,看看窗外。方向(我相信是用度来衡量的…)

编辑:在移动设备上,如果你打开键盘,那么上面可能会失败,所以可以使用屏幕。availHeight和屏幕。availWidth,即使打开键盘也能给出适当的高度和宽度。

if(screen.availHeight > screen.availWidth){
    alert("Please use Landscape!");
}

关于window有一点需要注意。方向是,如果你不在移动设备上,它将返回未定义。一个好的检查方向的函数是这样的,其中x是window。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);

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

检查窗口。价值取向 比较innerHeight和innerWidth

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


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

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