|
|
|
|
@ -0,0 +1,67 @@
|
|
|
|
|
<!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.28rem;
|
|
|
|
|
}
|
|
|
|
|
.box1 {
|
|
|
|
|
width: 4rem;
|
|
|
|
|
height: 4rem;
|
|
|
|
|
background: #444;
|
|
|
|
|
margin: 0 auto;
|
|
|
|
|
}
|
|
|
|
|
.box2 {
|
|
|
|
|
width: 80%;
|
|
|
|
|
height: 3rem;
|
|
|
|
|
margin: 0.2rem 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>
|