1 //设置根元素字体 var win = window, doc = document; function setFontSize() { var winWidth =document.getElementsByTagName("html")[0].offsetWidth;
  //750这个数字是根据你的设计图的实际大小来的,所以值具体根据设计图的大小
  var size = (winWidth / 750) * 100;
  doc.documentElement.style.fontSize = (size < 100 ? size : 100) + 'px';
};
//这里我们给个定时器来实现页面加载完毕再进行字体设置
setTimeout(function() {
  //初始化
  setFontSize();
}, 100);
2 new function (){ var _self = this ; _self.width = 750; // 设置默认最大宽度 _self.fontSize = 100; // 默认字体大小 _self.widthProportion = function (){ var p = (document.body&&document.body.clientWidth||document.getElementsByTagName("html")[0].offsetWidth)/_self.width;return p>1?1:p<0.4?0.4:p; }; _self.changePage = function (){ document.getElementsByTagName("html")[0].setAttribute("style","font-size:"+_self.widthProportion()*_self.fontSize+"px !important"); } _self.changePage(); window.addEventListener('resize', function (){_self.changePage();}, false ); };
两种方案都是通过js去设置html的fontsize,当时很不理解为什么要设置默认宽度和默认字体大小。
思考了一下,理解为一种基准,比如屏幕375尺寸,对应的设计图比例就应该是1:2 所以设计图上100像素的元素,在页面上应该展示50像素。
写的时候因为设置默认字体胃100,所以要按0.01:1的比例去写,所以10px的元素要写成0.1ren。
至于问什么用100不用1,这样就可以直接写成10rem了 多好呢? 我刚开始也这么认为,后来设置了一下,尺寸全是错的,因为设置成1的默认比例,html的fontsize就会被设置为1px。不过页面最小字体是12px,所以会被默认设置为12px。计算也会按照12px去计算。