移動端橫屏
阿新 • • 發佈:2021-11-17
最近做了一個移動端的專案,其中需求是,使用者登入成功後,要求頁面內容是以橫屏的樣式來展示的。在這裡簡單的總結記錄下實現的方式。
css 的方式
-
媒體查詢 orientation
-
語法:
orientation:portrait | landscape
@media (orientation: portrait) {}
或者
@media (orientation: landscape) {}
portrait:指定輸出裝置中的頁面可見區域高度大於或等於寬度,即豎屏狀態。
landscape:除portrait值情況外,都是landscape。(viewport 處於橫向,即寬度大於高度。)
例項程式碼:@media (orientation: portrait) { .helper_main { transform-origin: 0 0; transform: rotateZ(90deg) translateY(-100%); } }
js 的方式
- 思路是:獲取檢視的寬高,通過比較寬和高的大小,改變元素的寬和高
const ele_width = document.documentElement.clientWidth; const ele_height = document.documentElement.clientHeight; const max = ele_width > ele_height ? ele_width : ele_height; const min = ele_width > ele_height ? ele_height : ele_width; const app_ele = document.getElementById('mobile_live'); app_ele.style.width = max + 'px'; app_ele.style.height = min + 'px';
相關的事件
-
orientationchange 事件,螢幕旋轉觸發的事件
window.addEventListener("orientationchange", function() {})
或者
window.onorientationchange = function() {}
-
window.orientation 獲取螢幕旋轉的角度
if (window.orientation == 0 || window.orientation == 180){ console.log('portrait'); } if (window.orientation == 90 || window.orientation == -90){ console.log('landscape'); }
-
screen.orientation.angle 獲取螢幕旋轉的角度
window.onorientationchange = function () { console.log( 'the orientation of the device is now ' + screen.orientation.angle ); };