我正在为移动设备建立一个网站。有一页特别适合在横屏模式下浏览。
是否有一种方法来检测访问该页面的用户是否在纵向模式下查看它,如果是的话,显示一条消息通知用户该页面在横向模式下查看最好?如果用户已经在横屏模式下查看,则不会出现任何消息。
所以基本上,我想让网站检测视口的方向,如果方向是纵向,然后显示一个警告消息,建议用户这个页面最好在横向模式下查看。
我正在为移动设备建立一个网站。有一页特别适合在横屏模式下浏览。
是否有一种方法来检测访问该页面的用户是否在纵向模式下查看它,如果是的话,显示一条消息通知用户该页面在横向模式下查看最好?如果用户已经在横屏模式下查看,则不会出现任何消息。
所以基本上,我想让网站检测视口的方向,如果方向是纵向,然后显示一个警告消息,建议用户这个页面最好在横向模式下查看。
当前回答
我认为更稳定的解决方案是使用屏幕而不是窗口,因为如果你要调整桌面电脑上的浏览器窗口大小,它可以是横向或纵向的。
if (screen.height > screen.width){
alert("Please use Landscape!");
}
其他回答
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; }
};
screen.orientation.addEventListener("change", function(e) {
console.log(screen.orientation.type + " " + screen.orientation.angle);
}, false);
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Rotation Test</title>
<link type="text/css" href="css/style.css" rel="stylesheet"></style>
<script src="js/jquery-1.5.min.js" type="text/javascript"></script>
<script type="text/javascript">
window.addEventListener("resize", function() {
// Get screen size (inner/outerWidth, inner/outerHeight)
var height = $(window).height();
var width = $(window).width();
if(width>height) {
// Landscape
$("#mode").text("LANDSCAPE");
} else {
// Portrait
$("#mode").text("PORTRAIT");
}
}, false);
</script>
</head>
<body onorientationchange="updateOrientation();">
<div id="mode">LANDSCAPE</div>
</body>
</html>
为了将所有这些伟大的注释应用到我的日常编码中,为了所有应用程序之间的连续性,我决定在我的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");
}
}
我用的是Android Chrome的“屏幕朝向API”
要查看当前的方向,请调用console.log(screen.orientation.type)(也可以调用screen.orientation.angle)。
结果:肖像-主|肖像-次|景观-主|景观-次
下面是我的代码,希望对大家有所帮助:
var m_isOrientation = ("orientation" in screen) && (typeof screen.orientation.lock == 'function') && (typeof screen.orientation.unlock == 'function');
...
if (!isFullscreen()) return;
screen.orientation.lock('landscape-secondary').then(
function() {
console.log('new orientation is landscape-secondary');
},
function(e) {
console.error(e);
}
);//here's Promise
...
screen.orientation.unlock();
我只测试了Android Chrome -好的