我正在为移动设备建立一个网站。有一页特别适合在横屏模式下浏览。
是否有一种方法来检测访问该页面的用户是否在纵向模式下查看它,如果是的话,显示一条消息通知用户该页面在横向模式下查看最好?如果用户已经在横屏模式下查看,则不会出现任何消息。
所以基本上,我想让网站检测视口的方向,如果方向是纵向,然后显示一个警告消息,建议用户这个页面最好在横向模式下查看。
我正在为移动设备建立一个网站。有一页特别适合在横屏模式下浏览。
是否有一种方法来检测访问该页面的用户是否在纵向模式下查看它,如果是的话,显示一条消息通知用户该页面在横向模式下查看最好?如果用户已经在横屏模式下查看,则不会出现任何消息。
所以基本上,我想让网站检测视口的方向,如果方向是纵向,然后显示一个警告消息,建议用户这个页面最好在横向模式下查看。
当前回答
有一种方法可以检测用户是否使用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).on("orientationchange",function( event ){
alert(screen.orientation.type)
});
经过一些实验,我发现旋转一个方向感知设备总是会触发浏览器窗口的调整大小事件。因此,在你的resize处理程序中,简单地调用这样一个函数:
function is_landscape() {
return (window.innerWidth > window.innerHeight);
}
感谢托比戴维斯的指引。
要实现基于移动设备方向的警报消息,您需要在函数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);
这就是我用的。
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);