index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0,minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>使用REM</title>
<style type="text/css">
/*
1 rem,em区别
rem指跟元素(html)的字体大小(体验效果可以打开谷歌浏览器--手机模式--切换不同手机型号会 看到根元素html的字体大小不一样。)。
em单位是当前元素字体的大小。
2 算法:当前屏幕宽度/设计稿宽度
1)使用屏幕宽度处理设计稿,宽度就会得到设计稿要缩放多少倍,就可以占满当前屏幕。
如:750的设计稿,放在375的屏幕上,就需要缩放0.5倍
750的设计稿,放在414的屏幕上,就需要缩放0.552倍
3 优化算法:当前屏幕宽度/设(计稿宽度 /100)
1) 需要注意部分浏览器的字体是不能小于12的
2)这时可以把设计稿缩小100倍,在使用rem单位的时候也缩小100倍即可。
*/
/*
1 设计图宽度width 560px,高度66px;
2 引用flexible.js之后 源码多除了一个 100,所以变成了5.6rem ,0.66rem
*/
.title{
width: 5.60rem;
height: 0.66rem;
background-color: #00A1FF;
}
</style>
</head>
<body>
<div class="title"></div>
<script src="./flexible.js"></script>
</body>
</html>
flexible.js
;function resetFontSize(){
var designWidth = 750;
var width = document.documentElement.clientWidth || window.innerWidth;
var currentFontSize = width /(designWidth / 100);
document.documentElement.style.fontSize = currentFontSize + 'px'
//默认设置body字体 用rem和px 都可以
//document.querySelector('body').style.fontSize = 16+'px';
//document.querySelector('body').style.fontSize = 0.29+'rem';
}
window.onresize = function(){
resetFontSize();
}
resetFontSize();
/**
//可以用以下试试
;function resetFontSize(){
var designWidth = 750;
var deviceWidth = document.documentElement.clientWidth || window.innerWidth;
if(deviceWidth >= 750){
deviceWidth = 750;
}
if(deviceWidth <= 320){
deviceWidth = 320;
}
var currentFontSize = deviceWidth /(designWidth / 100);
document.documentElement.style.fontSize = currentFontSize + 'px'
//默认设置body字体 用rem和px 都可以
document.querySelector('body').style.fontSize = 16+'px';
//document.querySelector('body').style.fontSize = 0.29+'rem';
}
window.onresize = function(){
resetFontSize();
}
resetFontSize();
**/