1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| <!DOCTYPE html> <html lang="en">
<head> <meta charset="UTF-8"> <title>大屏适配方案</title> <style> * { margin: 0; height: 0; } #app { background-color: red; width: 1920px; height: 968px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
transform-origin: left top; } </style> </head>
<body> <div id="app"></div> <script> let baseWidth = 1920 let baseHeight = 968 let timer = null
let baseRate = (baseWidth / baseHeight).toFixed(5)
let scale = { width: '1', height: '1' }
const resizeDraw = () => { let innerWidth = window.innerWidth let innerHeight = window.innerHeight let innerRate = parseFloat((innerWidth / innerHeight).toFixed(5)) if (innerRate > baseRate) { let rate = (innerHeight / baseHeight).toFixed(5) scale.width = rate scale.height = rate } else { let rate = (innerWidth / baseWidth).toFixed(5) scale.width = rate scale.height = rate } document.getElementById("app").style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)` }
const resize = () => { clearTimeout(timer) timer = setTimeout(() => { resizeDraw() }, 200) }
resizeDraw() window.addEventListener('resize', resize) </script> </body>
</html>
|
!!! 尽量不要用vh、vw这种单位,否则 resize 后会有问题