我有一个拥有移动设备样式表的网站:
<link rel="stylesheet" href="css/mobile.css" media="handheld">
我还使用jQuery来检测移动设备并相应地修改功能。
但我想知道是否有一种方法可以强制横屏方向并禁用自动旋转?无论是CSS还是jQuery解决方案都可以。
谢谢!
我有一个拥有移动设备样式表的网站:
<link rel="stylesheet" href="css/mobile.css" media="handheld">
我还使用jQuery来检测移动设备并相应地修改功能。
但我想知道是否有一种方法可以强制横屏方向并禁用自动旋转?无论是CSS还是jQuery解决方案都可以。
谢谢!
使用媒体查询来测试设备方向,在纵向样式表中隐藏所有内容并显示一个消息,说明应用只能在横向模式下工作。
<link rel="stylesheet" type="text/css" href="css/style_l.css" media="screen and (orientation: landscape)">
<link rel="stylesheet" type="text/css" href="css/style_p.css" media="screen and (orientation: portrait)">
我认为这是最佳方法
<div id="block_land">Turn your device in landscape mode.</div>
#block_land{position:absolute; top:0; left:0; text-align:center; background:white; width:100%; height:100%; display:none;}
然后添加一些JavaScript代码来检测方向。
function testOrientation() {
document.getElementById('block_land').style.display = (screen.width>screen.height) ? 'none' : 'block';
}
不要忘记在onload和onorientationchange中测试方向,也许在您的body标签中。
<body onorientationchange="testOrientation();" onload="testOrientation();">
如果这个解决方案对您有用,请告诉我。
我认为最好的方法是使用脚本,以便在用户更改时它也随之更改。我修改了这个脚本,使得在竖屏模式下旋转页面的主要 DIV,迫使用户切换。除非他们想要将头歪向一边:
<script type="text/javascript">
(function () {
detectPortrait();
$(window).resize(function() {
detectPortrait("#mainView");
});
function detectPortrait(mainDiv) {
if (screen.width < screen.height) {
$(mainDiv).addClass("portrait_mode");
}
else {
$(mainDiv).removeClass("portrait_mode");
}
}
})();
</script>
<style type="text/css">
.portrait_mode {
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
}
</style>
orientation: portrait
媒体查询来触发它也可以起作用。 - Mr Lister强制横屏的简单方法是在CSS代码中设置最小和最大宽度,尝试使用以下代码:
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation:portrait) {
body {
-webkit-transform: rotate(90deg);
width: 100%;
height: 100%;
overflow: hidden;
position: absolute;
top: 0;
left: 0;
}}
您可以通知用户更改方向并隐藏屏幕。然后感应方向变化并重新加载页面。 以下代码应放置在页面模板的末尾或页脚。
这是为了告知用户应旋转设备,当页面处于纵向状态时,它会隐藏内容。您应确认“.content”是页面上正确的选择器。
if(screen.availHeight > screen.availWidth){
jQuery( ".content" ).css( "display", "none" );
var newLine = "\r\n"
var msg = "Please use Landscape!"
msg += newLine;
msg += "(Turn your phone 90 degrees)";
msg += newLine;
msg += "and wait a seconds,";
msg += newLine;
msg += "for the page to reload.";
alert(msg);
}
当用户旋转设备时,这将重新加载隐藏的页面。
jQuery(window).on("orientationchange",function(){
location.reload();
});
我尝试了以下代码,它强制浏览器使用竖屏模式:
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0" />
这段代码已在iPhone和另一台移动设备上进行了测试。