1. 程式人生 > 其它 >H5 - 強制橫屏

H5 - 強制橫屏

1、常用的小遊戲開發挺多都是橫屏顯示,所以我們H5開發同樣也需要橫屏顯示,所以我分享一個強制橫屏的demo,html的內容如下:

<body style="margin: 0px;height: 100%;padding: 0;" >
        <div id="print">
            <div id="changeIt">
               11111111
            </div>
        </div>
    </body>

2、通過媒體查詢,區分在橫屏和豎屏的狀態下使用的css,程式碼如下:

            /* 豎屏   orientation: portrait 代表豎屏的狀態下*/
            @media screen and (orientation: portrait) {
                html {
                    width: 100%;
                    height: 100%;
                    overflow: hidden;
                }
                body {
                    width: 
100%; height: 100%; overflow: hidden; } #print { position: absolute; } } /* 橫屏 orientation: landscape代表手機在橫屏的狀態下 */ @media screen and (orientation: landscape) { html { width:
100%; height: 100%; } body { width: 100%; height: 100%; } #print { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } }

3、接下來是js程式碼,大家可以手動拷貝一份:

<script>
    // 試試橫屏
    let width = document.documentElement.clientWidth;
    let height = document.documentElement.clientHeight;
    if (width < height) {
        console.log(width + "," + height);
        $print = $('#print');
        $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";
    console.log(evt, 'evt')
    window.addEventListener(evt, function() {
        setTimeout(function() {
            var width = document.documentElement.clientWidth;
            var height = document.documentElement.clientHeight;

            $print = $('#print');
            $videoIntroduce = $('#videoIntroduce')
            $toVideoBack = $('#toVideoBack')
            $backgroundImg = $('.backgroundImg')
            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%');
            }
        }, 500)
    }, false);
    
</script>

4、我們先用瀏覽器手機模式測試一下,效果圖如下(橫屏跟豎屏都是橫屏的模式):         --真機測試同樣也達到了強制橫屏的效果