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

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

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


当前回答

为了将所有这些伟大的注释应用到我的日常编码中,为了所有应用程序之间的连续性,我决定在我的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");
  }
}

其他回答

为了将所有这些伟大的注释应用到我的日常编码中,为了所有应用程序之间的连续性,我决定在我的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");
  }
}

我不同意投票最多的答案。用屏风而不是窗户

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

是正确的方法。如果用窗口计算。高度,你在Android上就会遇到麻烦。当键盘打开时,窗口收缩。所以用screen代替window。

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

不要尝试固定窗口。方向查询(0,90等并不意味着纵向,横向等):

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

即使在iOS7上,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将被触发,当用户使用纵向模式时,警报将弹出。

你也可以用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上测试。