大屏适配(scale)

225 阅读1分钟
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="css/style.css">

    <style>
        .box {
            background-color: rgb(110, 112, 112);
            position: absolute;
            top: 50%;
            left: 50%;

            color: #fff;
            font-size: 20px;
        }
    </style>
</head>

<body>
    <div class="box">123</div>

    <script>
        function resize_init() {
            let dw = document.documentElement.clientWidth;
            let dh = document.documentElement.clientHeight;
            // let ddw = 1440;
            // let ddh = 1024;
            let ddw = 1920;
            let ddh = 1080;

            const scale = dw / dh > ddw / ddh ? (dh / ddh) : (dw / ddw);
            console.log(`屏幕宽高${dw}x${dh},缩放${scale}`);
            document.querySelector('.box').style.transform = `translate(-50%,-50%) scale(${scale})`;
            document.querySelector('.box').style.width = ddw+'px';
            document.querySelector('.box').style.height = ddh+'px';
            document.querySelector('.box').innerText = `屏幕宽高${dw}x${dh},缩放${scale}`;
        }
        resize_init();

        window.addEventListener('resize', resize_init);
    </script>
</body>

</html>