我正在为移动设备建立一个网站。有一页特别适合在横屏模式下浏览。
是否有一种方法来检测访问该页面的用户是否在纵向模式下查看它,如果是的话,显示一条消息通知用户该页面在横向模式下查看最好?如果用户已经在横屏模式下查看,则不会出现任何消息。
所以基本上,我想让网站检测视口的方向,如果方向是纵向,然后显示一个警告消息,建议用户这个页面最好在横向模式下查看。
我正在为移动设备建立一个网站。有一页特别适合在横屏模式下浏览。
是否有一种方法来检测访问该页面的用户是否在纵向模式下查看它,如果是的话,显示一条消息通知用户该页面在横向模式下查看最好?如果用户已经在横屏模式下查看,则不会出现任何消息。
所以基本上,我想让网站检测视口的方向,如果方向是纵向,然后显示一个警告消息,建议用户这个页面最好在横向模式下查看。
当前回答
有几种方法可以做到,例如:
检查窗口。价值取向 比较innerHeight和innerWidth
您可以采用下面的方法之一。
检查设备是否处于纵向模式
function isPortrait() {
return window.innerHeight > window.innerWidth;
}
检查设备是否处于横屏模式
function isLandscape() {
return (window.orientation === 90 || window.orientation === -90);
}
示例使用
if (isPortrait()) {
alert("This page is best viewed in landscape mode");
}
我如何检测方向变化?
$(document).ready(function() {
$(window).on('orientationchange', function(event) {
console.log(orientation);
});
});
其他回答
<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>
不要尝试固定窗口。方向查询(0,90等并不意味着纵向,横向等):
http://www.matthewgifford.com/blog/2011/12/22/a-misconception-about-window-orientation/
即使在iOS7上,0也不总是竖屏的,这取决于你进入浏览器的方式
有几种方法可以做到,例如:
检查窗口。价值取向 比较innerHeight和innerWidth
您可以采用下面的方法之一。
检查设备是否处于纵向模式
function isPortrait() {
return window.innerHeight > window.innerWidth;
}
检查设备是否处于横屏模式
function isLandscape() {
return (window.orientation === 90 || window.orientation === -90);
}
示例使用
if (isPortrait()) {
alert("This page is best viewed in landscape mode");
}
我如何检测方向变化?
$(document).ready(function() {
$(window).on('orientationchange', function(event) {
console.log(orientation);
});
});
你也可以用window。matchMedia,我使用并喜欢它,因为它非常类似于CSS语法:
if (window.matchMedia("(orientation: portrait)").matches) {
// you're in PORTRAIT mode
}
if (window.matchMedia("(orientation: landscape)").matches) {
// you're in LANDSCAPE mode
}
在iPad 2上测试。
不是270,而是-90(-90)。