說明:這個的原文章來自於https://www.jianshu.com/p/9c3264f4a405 ,我做點點補充 ,謝謝原鏈接的小姐姐
最近公司是要我做一個h5的小視頻,因為是視頻接視頻,並且源文件就是橫屏的,所以要求點擊網址一進入就是橫屏的狀態。。。。。
<body style="margin: 0px;height: 100%;padding: 0;" class="webpBack"> <span id="print" > <span id="changeIt"> 啦啦啦 </span> </span> </body>
下面的代碼要注意啦~~~~注意點:因為你在自己的代碼上去套這個樣式,你可以在豎屏的情況下設一個顏色 ,橫屏的時候設另外一個顏色,在這兩種狀態下去調css,還有我當初習慣了寫行內樣式,半天出不來~~~~所以最好用class。。。。
/* 豎屏 */ @media screen and (orientation: portrait) { html{ width : 100% ; height : 100% ; overflow : hidden; /* background-color:yellow; */ } body{ width : 100% ; height : 100% ; overflow : hidden; } #print{ position : absolute ; } .enterDiv{ height: 100%; width: 100%; position: relative; left: 0; } } /* 橫屏 */ @media screen and (orientation: landscape) { html{ width : 100% ; height : 100% ; /* background-color:red; */ } body{ width : 100% ; height : 100% ; } #print{ position : absolute ; top : 0 ; left : 0 ; width : 100% ; height : 100% ; } .backgroundEnter{ width: 100%; position: absolute; top: 0; left: 0; } } #print span{ margin: auto ; margin-top : 20px ; text-align: center; }
橫屏的js
下面要注意的是:剛開始我的蘋果6s打死都不起作用,但是別人的6s可以,大部分的安卓機起作用,我的6s出現的狀況是第一次豎屏是正常的,進入橫屏狀態也是正常的,當我回來到豎屏的時候,就不行了,為什么?下面的if-else的判斷,else里面死都進不去,我都想重寫全部的css了,我也懷疑過是不是document.documentElement.clientWidth;是不是不適合去獲取寬高,並不是,而是在轉屏的時候,手機需要切換結束后獲取到的寬高才是正確的,所以監聽的里面我們做一個0.5秒的延遲就可以了 ........
<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() { // window.localtion.reload(); 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);
之前有看到評論說做延遲,但是不知道出現什么樣的情況去做,也不知道為什么,錯過就知道了