我正在为移动设备建立一个网站。有一页特别适合在横屏模式下浏览。
是否有一种方法来检测访问该页面的用户是否在纵向模式下查看它,如果是的话,显示一条消息通知用户该页面在横向模式下查看最好?如果用户已经在横屏模式下查看,则不会出现任何消息。
所以基本上,我想让网站检测视口的方向,如果方向是纵向,然后显示一个警告消息,建议用户这个页面最好在横向模式下查看。
我正在为移动设备建立一个网站。有一页特别适合在横屏模式下浏览。
是否有一种方法来检测访问该页面的用户是否在纵向模式下查看它,如果是的话,显示一条消息通知用户该页面在横向模式下查看最好?如果用户已经在横屏模式下查看,则不会出现任何消息。
所以基本上,我想让网站检测视口的方向,如果方向是纵向,然后显示一个警告消息,建议用户这个页面最好在横向模式下查看。
当前回答
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事件。
其他回答
获得方向(在任何时间在你的js代码)通过
window.orientation
当窗口。方向返回0或180则处于竖屏模式,返回90或270则处于横屏模式。
另一种基于宽度/高度的比较来确定方向的方法:
var mql = window.matchMedia("(min-aspect-ratio: 4/3)");
if (mql.matches) {
orientation = 'landscape';
}
你在"resize"事件上使用它:
window.addEventListener("resize", function() { ... });
有一种方法可以检测用户是否使用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有一点需要注意。方向是,如果你不在移动设备上,它将返回未定义。一个好的检查方向的函数是这样的,其中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);
这就是我用的。
function getOrientation() {
// if window.orientation is available...
if( window.orientation && typeof window.orientation === 'number' ) {
// ... and if the absolute value of orientation is 90...
if( Math.abs( window.orientation ) == 90 ) {
// ... then it's landscape
return 'landscape';
} else {
// ... otherwise it's portrait
return 'portrait';
}
} else {
return false; // window.orientation not available
}
}
实现
window.addEventListener("orientationchange", function() {
// if orientation is landscape...
if( getOrientation() === 'landscape' ) {
// ...do your thing
}
}, false);