我正在为移动设备建立一个网站。有一页特别适合在横屏模式下浏览。
是否有一种方法来检测访问该页面的用户是否在纵向模式下查看它,如果是的话,显示一条消息通知用户该页面在横向模式下查看最好?如果用户已经在横屏模式下查看,则不会出现任何消息。
所以基本上,我想让网站检测视口的方向,如果方向是纵向,然后显示一个警告消息,建议用户这个页面最好在横向模式下查看。
我正在为移动设备建立一个网站。有一页特别适合在横屏模式下浏览。
是否有一种方法来检测访问该页面的用户是否在纵向模式下查看它,如果是的话,显示一条消息通知用户该页面在横向模式下查看最好?如果用户已经在横屏模式下查看,则不会出现任何消息。
所以基本上,我想让网站检测视口的方向,如果方向是纵向,然后显示一个警告消息,建议用户这个页面最好在横向模式下查看。
当前回答
下面是我根据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") }
其他回答
CCS只
@media (max-width: 1024px) and (orientation: portrait){ /* tablet and smaller */
body:after{
position: absolute;
z-index: 9999;
width: 100%;
top: 0;
bottom: 0;
content: "";
background: #212121 url(http://i.stack.imgur.com/sValK.png) 0 0 no-repeat; /* replace with an image that tells the visitor to rotate the device to landscape mode */
background-size: 100% auto;
opacity: 0.95;
}
}
在某些情况下,你可能想要添加一小段代码,以便在访问者旋转设备后重新加载到页面,这样CSS就能正确呈现:
window.onorientationchange = function() {
var orientation = window.orientation;
switch(orientation) {
case 0:
case 90:
case -90: window.location.reload();
break; }
};
经过一些实验,我发现旋转一个方向感知设备总是会触发浏览器窗口的调整大小事件。因此,在你的resize处理程序中,简单地调用这样一个函数:
function is_landscape() {
return (window.innerWidth > window.innerHeight);
}
有些设备不提供orientationchange事件,但会触发窗口的resize事件:
// Listen for resize changes
window.addEventListener("resize", function() {
// Get screen size (inner/outerWidth, inner/outerHeight)
}, false);
没有orientationchange事件那么明显,但是工作得很好。请在这里查看
if(window.innerHeight > window.innerWidth){
alert("Please use Landscape!");
}
jQuery Mobile有一个事件来处理这个属性的变化…如果你想警告如果有人旋转后-定向变化
另外,在谷歌搜索之后,看看窗外。方向(我相信是用度来衡量的…)
编辑:在移动设备上,如果你打开键盘,那么上面可能会失败,所以可以使用屏幕。availHeight和屏幕。availWidth,即使打开键盘也能给出适当的高度和宽度。
if(screen.availHeight > screen.availWidth){
alert("Please use Landscape!");
}
下面是我根据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") }