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

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

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


当前回答

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

这个解决方案也适用于android设备。我检查了android原生浏览器(互联网浏览器)和Chrome浏览器,甚至是旧版本的浏览器。

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

其他回答

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

这个解决方案也适用于android设备。我检查了android原生浏览器(互联网浏览器)和Chrome浏览器,甚至是旧版本的浏览器。

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

感谢托比戴维斯的指引。

要实现基于移动设备方向的警报消息,您需要在函数setHeight(){中实现以下脚本

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

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

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

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