前言
在移动端中我们经常碰到横屏竖屏的问题,那么如何去判断或者针对横屏、竖屏来写不同的代码呢。
首先在head中加入如下代码:
<meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
一、页面横屏
1、CSS判断横屏竖屏
1.1 写在同一个CSS文件中
@media screen and (orientation: portrait) {
/*竖屏 css*/
}
@media screen and (orientation: landscape) {
/*横屏 css*/
}
1.2 分开写在2个CSS文件中
竖屏
引用方式
<link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css">
横屏
引用方式
<link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css">
2、JS判断横屏竖屏
//判断手机横竖屏状态:
window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", function() {
if (window.orientation === 180 || window.orientation === 0) {
alert('竖屏状态!');
}
if (window.orientation === 90 || window.orientation === -90 ){
alert('横屏状态!');
}
}, false);
//移动端的浏览器一般都支持window.orientation这个参数,通过这个参数可以判断出手机是处在横屏还是竖屏状态。
二、页面强制横屏显示
有这个需求这个是因为客户端将手机横屏的功能屏蔽掉了,所以只能强制将页面横屏显示了
以下是我的示例结构
<div class="horizontal-main">
horizontal-main
</div>
css:
.horizontal-main {
background: linear-gradient(168deg, #f4dcef, #feead1);
transform: rotate(90deg);
transform-origin: 50% 50%;
top: 146px;
width: 667px;
left: -146px;
height: 375px;
overflow-x: hidden;
overflow-y: auto;
}
js:
$(function(){
var width = document.documentElement.scrollWidth;
var height = document.documentElement.scrollHeight;
if( width < height ){
$horiM = $('.horizontal-main');
$horiM.width(height);
$horiM.height(width);
$horiM.css('top', (height-width)/2 );
$horiM.css('left', 0-(height-width)/2 );
}
})
注意:这个方法只适合一屏展示的页面,不适合带有滚动条的页面。