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

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

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


当前回答

我把两个解决方案结合起来,对我来说效果很好。

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

其他回答

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

大卫·沃尔什的方法更好,更切中要害。

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

在这些更改期间,窗口。方向属性可能会改变。值为0表示纵向视图,-90表示设备横向向右旋转,90表示设备横向向左旋转。

http://davidwalsh.name/orientation-change

这是对之前答案的扩展。我发现的最好的解决方案是创建一个无害的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 + "!");
    });
});

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

获得方向(在任何时间在你的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!");
}