标图宽度尺寸/新设备宽度 = 旧font-size/新font-size
旧/新 = 100/val
旧val = 新100
val = (新*100)/旧
新页面的font-size = 新设备宽度 * 旧font-size * 标图宽尺寸
新设备视图宽度使用document.documentElement.clientWidth获取
需求:目前标图宽度为400,其中有个100px的盒子,当宽度为800时,盒子自动变为200px
1、先写一个盒子 100*100的红盒子
<style>
.test {
width: 100px;
height: 100px;
background-color: brown;
}
</style>
<body>
<div class="test">
</div>
</body>
2、设定html中font-size为100px,方便计算 ,test盒子也变成了rem
<style>
html {
font-size: 100px; //设定旧font-size
}
.test {
width: 1rem; //绝对单位px变成相对单位rem
height: 1rem;
background-color: brown;
}
</style>
<body>
<div class="test">
</div>
</body>
3、在script中进行计算
window.onresize = function () { //当window的视图变化
//获取新视图的font-size = 新视图宽尺寸 * 旧font-size /原本的宽尺寸
let fs = document.documentElement.clientWidth * 100 / 400
//将新视图font-size赋值给新视图,保证test盒子的rem宽度准确
document.documentElement.style.fontSize = fs +'px'
}
完成!