<style>
.font{
font-size: .28rem
width: 4.00rem
height: 4.00rem
background: pink
}
</style>
<script>
(()=>{
function resize(){
let root = document.documentElement
let width=root.getBoundingClientRect().width
if (
/Android|webOS|iPhone|iPod|BlackBerry|WindowsCE/i.test(
navigator.userAgent
)
) {
if(width>750){
width = 750
}
root.style.fontSize = width/7.5+"px"
console.log(width,root.style.fontSize)
}else{
if(width>1920){
width = 1920
}
root.style.fontSize = width/19.20+"px"
console.log(width,root.style.fontSize)
}
}
resize()
let t = null
window.addEventListener("resize", function() {
clearTimeout(t)
t = setTimeout(resize(), 300)
})
})()
</script>
/*
rem 公式 (动态获取屏幕的宽度/设计稿的宽度)*100+"px",得出来得就是设备的根元素得fontSize
怎么动态获取屏幕的宽度
document.documentElement.getBoundingClientRect().width 返回元素的大小及其相对于视口的位置
100是怎么来的
答案:
根据元素大小来计算1rem到底等于多少px,如果根元素为100px,那么1rem=100px,2rem=200px
如果设备的宽度是750,给这个宽度为750px的设备的根元素设置为100px,那这样的话1rem = 100px了
移动端
例如 iPhone6
375 * 667 设备独立像素,屏幕尺寸
750 * 1334 设备像素,屏分辨率率
2 设备像素比 dpr=2
此时根元素的fontsize 50px
如果给页面设置宽200px 高200px fontSize:14px
结果:
width:4rem
在没有给设备的根元素设置px时
1rem = 16px,
2rem = 32px
*/