常见方案
- vh、vw方案:将所有的尺寸根据设计图换算成vw和vh
- scale方案:根据设计图的尺寸和当前屏幕的尺寸计算缩放的比例
- rem方案:根据设计图和屏幕尺寸计算根元素font-size,其他尺寸通过插件换算成rem
scale兼容的优缺点
优点:1、代码量极少,只需要处理一次container;2、其他各种图表不用单独进行适配
缺点:1、因为是根据ui进行等比例缩放,所以左右和上下可能会出现白边;2、放大倍数过大会导致图片等失真变模糊(可以让ui出8倍的图 然后整体也按照正常分辨率的8倍去编写,这样可以去极大的避免这种情况,缺点就是图片会变得很大,造成图片加载慢);3、缩放之后高德地图,百度地图、echarts等的事件热区会偏移。
代码示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.demo1 {
width: 1920px;
height: 1080px;
background-color: #f00;
transform-origin: top left;
margin-left: 50%;
}
</style>
</head>
<body style="overflow: hidden; width: 100vw; height: 100vh">
<div class="demo1"></div>
</body>
<script>
const calculateRatio = (width, height, el) => {
const baseWidth = width;
const baseHeight = height;
const baseRate = parseFloat(baseWidth / baseHeight).toFixed(5);
const currentRate = parseFloat(
window.innerWidth / window.innerHeight
).toFixed(5);
const scale = {
widthRatio: 1,
heightRatio: 1,
};
if (currentRate > baseRate) {
scale.widthRatio = parseFloat(
((window.innerHeight * baseRate) / baseWidth).toFixed(5)
);
scale.heightRatio = parseFloat(
(window.innerHeight / baseHeight).toFixed(5)
);
} else {
scale.heightRatio = parseFloat(
(window.innerWidth / baseRate / baseHeight).toFixed(5)
);
scale.widthRatio = parseFloat(
(window.innerWidth / baseWidth).toFixed(5)
);
}
el.style.transform = `scale(${scale.widthRatio}, ${scale.heightRatio}) translate(-50%, 0)`;
};
calculateRatio(1920, 1080, document.querySelector(".demo1"));
window.addEventListener("resize", () => {
calculateRatio(1920, 1080, document.querySelector(".demo1"));
});
</script>
</html>

总结
通过ui图的比例和当前屏幕显示的比例去计算需要缩放的大小倍数,如果当前的屏幕比例大于设计图的比例 那么就是宽度大于高度根据高度去计算缩放 反之则使用宽度去计算
