css + js 实现自适应16:9

551 阅读1分钟

css部分

<style>
    * {
        margin: 0;
        padding: 0;
        list-style: none;
    }
    html {
        height: 100%
    }
    body {
        height: 100%;
        background-color: black;
    }
    .body-width {
        height: 100%;
        background-color: black;
        width: 177.6vmin;
        min-height: 100vmin;
        margin: 0 auto;
    }
    .body-height {
        width: 100vw;
        height: 56.25vw;
        margin: 0 auto;
        position: relative;
        top: 50%;
        transform: translateY(-50%);
    }
</style>

js部分

        ! function () {
        let oBody = document.getElementsByTagName("div")[0]
        let _height = document.body.clientHeight
        let _width = document.body.clientWidth;
        if (_width / _height < (16 / 9)) {
            oBody.classList.remove('body-width')
            oBody.classList.add('body-height')
        } else {
            oBody.classList.remove('body-height')
            oBody.classList.add('body-width')
        }
    }()