#appRef {
width: 1920px; /* 设计图宽 */
height: 1080px; /* 设计图高 */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
transform-origin: left top;
overflow: hidden;
}
// * 默认缩放值
const scale = {
width: '1',
height: '1',
}
// * 设计稿尺寸(px)
const baseWidth = 1920
const baseHeight = 1080
// * 需保持的比例
const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5))
let drawTiming = null
calcRate()
window.addEventListener('resize', resize)
// * 初始化页面比例
function calcRate() {
const appRef = document.getElementById("appRef")
if (!appRef) return
// 当前宽高比
const currentRate = parseFloat((window.innerWidth / window.innerHeight).toFixed(5))
if (appRef) {
if (currentRate > baseProportion) {
// 表示更宽
scale.width = ((window.innerHeight * baseProportion) / baseWidth).toFixed(5)
scale.height = (window.innerHeight / baseHeight).toFixed(5)
appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
} else {
// 表示更高
scale.height = ((window.innerWidth / baseProportion) / baseHeight).toFixed(5)
scale.width = (window.innerWidth / baseWidth).toFixed(5)
appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
}
}
}
// * 窗口大小变化
function resize() {
clearTimeout(drawTiming)
// 加延迟是为了更好的看到变化的过程,不需要的可以不用
drawTiming = setTimeout(() => {
calcRate()
}, 200)
}
<div id="appRef">
内容
</div>
标签:scale,const,适配,50%,height,问题,window,大屏,appRef From: https://www.cnblogs.com/dlx609/p/17488450.html