手机网页保持竖屏

如果手机开启了自动横屏,那么网页就会跟着旋转,导致网页宽度变大,高度变小,页面布局不友好,我们可以通过判断屏幕方向 api,用 css 设置旋转。


HTML:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />
    <title>保持竖屏示例</title>
</head>
<body>
    <div id="app">
        <div class="page">
            <div>把手机横过来试试</div>
            <div>页面永远保持竖屏方向</div>
        </div>
    </div>
</body>
</html>

CSS:

body { margin: 0; }
.page { text-align: center; padding-top: 100px; }

@media screen and (orientation: landscape) {
    body { width: 100vh; height: 100vw; overflow: hidden; }
    .page.landscape-primary { transform: rotate(-90deg); transform-origin: top left; width: 100vh; height: 100vw; position: absolute; top: 100%; left: 0; }
    .page.landscape-secondary { transform: rotate(90deg); transform-origin: top left; width: 100vh; height: 100vw; position: absolute; top: 0; left: 100%; }
}

JS:

function fn_set_orientation() {
    var orientation = window.screen.orientation || window.screen.mozOrientation || window.screen.msOrientation;
    const div = document.querySelector('.page');
    console.log(orientation.type)
    switch (orientation.type) {
        case 'landscape-primary': {
            div.classList.remove('landscape-secondary');
            div.classList.add('landscape-primary');
            break;
        }
        case 'landscape-secondary': {
            div.classList.remove('landscape-primary');
            div.classList.add('landscape-secondary');
            break;
        }
        default: {
            div.classList.remove('landscape-primary');
            div.classList.remove('landscape-secondary');
            break;
        }
    }
}
window.addEventListener("orientationchange", function () {
    fn_set_orientation();
});
fn_set_orientation();

示例:

https://xoyozo.net/Demo/Orientation


xoyozo 4 个月前
转载请注明出处
云服务器 精选特惠
可能相关的内容