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

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

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


当前回答

iOS不更新屏幕。宽度和屏幕。方向改变时的高度。Android不更新窗口。当它改变方向时。

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

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事件。

其他回答

感谢托比戴维斯的指引。

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

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

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

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

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

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

另一种基于宽度/高度的比较来确定方向的方法:

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

你在"resize"事件上使用它:

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

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

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

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

我用的是Android Chrome的“屏幕朝向API”

要查看当前的方向,请调用console.log(screen.orientation.type)(也可以调用screen.orientation.angle)。

结果:肖像-主|肖像-次|景观-主|景观-次

下面是我的代码,希望对大家有所帮助:

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 -好的