You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
<!doctype html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" / >
< meta
name = "viewport"
content = "width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1"
/ >
< title > 动态设置根元素fontSize来适配rem< / title >
< style >
* {
padding : 0 ;
margin : 0 ;
box-sizing : border-box ;
}
body {
font-size : 0.28 rem ;
}
. box1 {
width : 4 rem ;
height : 4 rem ;
background : #444 ;
margin : 0 auto ;
}
. box2 {
width : 80 % ;
height : 3 rem ;
margin : 0.2 rem auto ;
background : yellow ;
}
< / style >
< / head >
< body >
< div class = "box1" > 盒子一< / div >
< div class = "box2" > 盒子二< / div >
< / body >
< / html >
< script >
//设计稿默认宽度尺寸
const WIDTH = 750 ;
//px转换为rem的放大倍率
const SCALE = 100 ;
const setView = ( ) => {
/**
* document.documentElement获取文档的根节点, 即html元素
* 设置html标签的fontSize
**/
document . documentElement . style . fontSize = ( SCALE * screen . width ) / WIDTH + 'px' ;
} ;
/**
* 监听屏幕方向变化, 调用setView重新计算
**/
window . onorientationchange = setView ;
/**
* 监听浏览器尺寸发生变化, 调用setView重新计算
**/
window . addEventListener ( 'resize' , setView ) ;
/**
* 页面加载时, 执行一次setView设置fontSize
**/
setView ( ) ;
< / script >