移动端页面横屏和强制横屏适配

前言

在移动端中我们经常碰到横屏竖屏的问题,那么如何去判断或者针对横屏、竖屏来写不同的代码呢。
首先在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 );
    } 
})

注意:这个方法只适合一屏展示的页面,不适合带有滚动条的页面。

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值