开始前:一定要记住,在iphone5下,1rem=16px;
图示:

下面开始三个步骤:
1.获取html的宽
操作代码:
let htmlwidth=document.documentElement.clientWidth || document.body.clientWidth;

2.获取htmlDom元素
let htmlDom=document.getElementByTagName('html')[0]

3.设置html样式
htmlDom.style.fontSize=htmlwith/20+'px';
完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
.test{
width: 20rem;
height: 10rem;
background-color: skyblue;
text-align: center;
}
.hello{
color: red;
font-size: 1rem;
}
</style>
<body>
<div class="test">
<div class="hello">hello JSPang</div>
</div>
</body>
</html>
<script>
let htmlwidth=document.documentElement.clientWidth || document.body.clientWidth;
console.log(htmlwidth);
let htmlDom=document.getElementsByTagName("html")[0]
console.log(htmlDom);
htmlDom.style.fontSize=htmlwidth/20+'px';
</script>
效果:点击不同的设备后刷新,都可以适配.

上面再进行优化:添加监听事件,让它自动监听窗口变化动态改变.
完整代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
.test{
width: 20rem;
height: 10rem;
background-color: skyblue;
text-align: center;
}
.hello{
color: red;
font-size: 1rem;
}
</style>
<body>
<div class="test">
<div class="hello">hello JSPang</div>
</div>
</body>
</html>
<script>
function gethtmlfontsize(){
let htmlwidth=document.documentElement.clientWidth || document.body.clientWidth;
console.log(htmlwidth);
let htmlDom=document.getElementsByTagName("html")[0]
console.log(htmlDom);
htmlDom.style.fontSize=htmlwidth/20+'px';
}
gethtmlfontsize();
window.addEventListener('resize',gethtmlfontsize)
</script>
效果:

上面是参考iphone5的320宽的写法,iphone678代码如下:
<script>
(function (doc, win) {
var docEl = win.document.documentElement;
var resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize';
var refreshRem = function () {
var clientWidth = win.innerWidth
|| doc.documentElement.clientWidth
|| doc.body.clientWidth;
console.log(clientWidth)
if (!clientWidth) return;
var fz;
var width = clientWidth;
fz = 16 * width / 375;
docEl.style.fontSize = fz + 'px';
};
if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, refreshRem, false);
doc.addEventListener('DOMContentLoaded', refreshRem, false);
refreshRem();
})(document, window);
</script>
补充:禁止客户双指缩放办法

最后附上一个更完美的解决方案(用别人写好的hotcss.js文件,你就可以直接写px像素,它会自动帮你转成rem):
我的收藏的hotcss.js文件地址
hotcss.js文件拷贝到viewport.js里,然后在webpack.config.js里面引入即可.
