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

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

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


当前回答

下面是我根据David Walsh的文章(检测移动设备的方向变化)找到的最好的方法。

if ( window.matchMedia("(orientation: portrait)").matches ) {  
   alert("Please use Landscape!") 
}

解释:

match media()是一个本地方法,允许您定义媒体查询规则并在任何时间点检查其有效性。

我发现在这个方法的返回值上附加一个onchange侦听器很有用。例子:

var mediaQueryRule = window.matchMedia("(orientation: portrait)")
mediaQueryRule.onchange = function(){ alert("screen orientation changed") }

其他回答

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

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

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

即使在iOS7上,0也不总是竖屏的,这取决于你进入浏览器的方式

$(window).on("orientationchange",function( event ){
    alert(screen.orientation.type)
});
//see also http://stackoverflow.com/questions/641857/javascript-window-resize-event
//see also http://mbccs.blogspot.com/2007/11/fixing-window-resize-event-in-ie.html
/*
Be wary of this:
While you can just hook up to the standard window resize event, you'll find that in IE, the event is fired once for every X and once for every Y axis movement, resulting in a ton of events being fired which might have a performance impact on your site if rendering is an intensive task.
*/

//setup 
window.onresize = function(event) {
    window_resize(event);
}

//timeout wrapper points with doResizeCode as callback
function window_resize(e) { 
     window.clearTimeout(resizeTimeoutId); 
     resizeTimeoutId = window.setTimeout('doResizeCode();', 10); 
}

//wrapper for height/width check
function doResizeCode() {
    if(window.innerHeight > window.innerWidth){
        alert("Please view in landscape");
    }
}

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

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

}, false);

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