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
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>autofit-scale</title> <style> html, body, div { padding: 0; margin: 0; } body { overflow: hidden; } .container { background-color: black; color: white; width: 1920px; height: 1080px; position: relative; } .right-b { position: absolute; right: 0; bottom: 0; } </style> </head> <body> <div class="container"> 这里是大屏 <div class="right-b">这里是大屏</div> </div> <script> autofitScale('.container', { width: 1920, height: 1080 }) function autofitScale(selector, options) { const el = document.querySelector(selector) const { width, height } = options el.style.transformOrigin = 'left top' el.style.transition = 'transform 0.3s' function init() { const scaleX = window.innerWidth / width const scaleY = window.innerHeight / height const scale = Math.min(scaleX, scaleY) const left = (window.innerWidth - width * scale) / 2 const top = (window.innerHeight - height * scale) / 2 el.style.transform = `translate(${left}px, ${top}px) scale(${scale})` } init() window.addEventListener('resize', debounce(init, 300)) }
function debounce(fn, delay) { let timer return function(...args) { if (timer) clearTimeout(timer) timer = setTimeout(() => { fn.apply(this, args) }, delay) } } } } </script> </body> </html>
|