我正在为移动设备建立一个网站。有一页特别适合在横屏模式下浏览。
是否有一种方法来检测访问该页面的用户是否在纵向模式下查看它,如果是的话,显示一条消息通知用户该页面在横向模式下查看最好?如果用户已经在横屏模式下查看,则不会出现任何消息。
所以基本上,我想让网站检测视口的方向,如果方向是纵向,然后显示一个警告消息,建议用户这个页面最好在横向模式下查看。
我正在为移动设备建立一个网站。有一页特别适合在横屏模式下浏览。
是否有一种方法来检测访问该页面的用户是否在纵向模式下查看它,如果是的话,显示一条消息通知用户该页面在横向模式下查看最好?如果用户已经在横屏模式下查看,则不会出现任何消息。
所以基本上,我想让网站检测视口的方向,如果方向是纵向,然后显示一个警告消息,建议用户这个页面最好在横向模式下查看。
当前回答
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; }
};
其他回答
不是270,而是-90(-90)。
//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");
}
}
有一种方法可以检测用户是否使用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将被触发,当用户使用纵向模式时,警报将弹出。
另一种基于宽度/高度的比较来确定方向的方法:
var mql = window.matchMedia("(min-aspect-ratio: 4/3)");
if (mql.matches) {
orientation = 'landscape';
}
你在"resize"事件上使用它:
window.addEventListener("resize", function() { ... });
不要尝试固定窗口。方向查询(0,90等并不意味着纵向,横向等):
http://www.matthewgifford.com/blog/2011/12/22/a-misconception-about-window-orientation/
即使在iOS7上,0也不总是竖屏的,这取决于你进入浏览器的方式