Javascript前端攻城狮

移动端如何让页面强制横屏

2018-02-10  本文已影响1451人  一名有马甲线的程序媛

移动设备可以旋转屏幕,但如何做到就算旋转手机页面始终横屏显示呢?现在我们就来搞一下~
首先取得屏幕内可用区域的宽高,然后根据宽高的关系来判断是横屏还是竖屏。如果是竖屏,就把div的宽高设置成横屏的高宽,然后旋转。
so easy 吧~ 上代码!

html:
    <!-- 就是一个div -->
    <div class="bg"></div>
css:
<style>
    *{
        padding:0;
        margin:0;
    }
    .bg{
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: url(pic.jpg) no-repeat #000;
        background-size: cover; /* 铺满屏幕,屏幕变小,图片可能显示不下 */
        background-size: 100% 100%; /* 铺满屏幕,随屏幕变化而变化比例,图片可能被拉伸 */
    }
    @media screen and (orientation: portrait) { /* 竖屏 */

    } 
    @media screen and (orientation: landscape) { /* 横屏 */

    }
</style>
js:
<script>

// 直接在最外层的div调用该函数即可
changeOrientation($('.bg'));

function changeOrientation( $print ){  
    var width = document.documentElement.clientWidth;
    var height =  document.documentElement.clientHeight;
    if( width < height ){
      // 竖屏
      $print.width(height);
      $print.height(width);
      $print.css('top',  (height-width)/2 );
      $print.css('left',  0-(height-width)/2 );
      $print.css('transform' , 'rotate(90deg)');
      $print.css('transform-origin' , '50% 50%');
    } 
 
    var evt = "onorientationchange" in window ? "orientationchange" : "resize";
      
    window.addEventListener(evt, function() {
        console.log(evt);
        setTimeout( function(){
            var width = document.documentElement.clientWidth;
             var height =  document.documentElement.clientHeight;
             if( width > height ){
               // 横屏
                $print.width(width);
                $print.height(height);
                $print.css('top',  0 );
                $print.css('left',  0 );
                $print.css('transform' , 'none');
                $print.css('transform-origin' , '50% 50%');
             }
             else{
                // 竖屏
                $print.width(height);
                $print.height(width);
                $print.css('top',  (height-width)/2 );
                $print.css('left',  0-(height-width)/2 );
                $print.css('transform' , 'rotate(90deg)');
                $print.css('transform-origin' , '50% 50%');
             }
            
        }  , 300 );

    }, false);
}
</script>

效果图:


竖屏状态 横屏状态

详情请下载 demo
点击 查看原文

上一篇下一篇

猜你喜欢

热点阅读