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

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

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


当前回答

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

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

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

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

其他回答

你可以使用CSS3:

@media screen and (orientation:landscape)
{
   body
   {
      background: red;
   }
}

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

感谢托比戴维斯的指引。

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

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

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

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

有些设备不提供orientationchange事件,但会触发窗口的resize事件:

// Listen for resize changes
window.addEventListener("resize", function() {
    // Get screen size (inner/outerWidth, inner/outerHeight)

}, false);

没有orientationchange事件那么明显,但是工作得很好。请在这里查看