方式一:
<script>
fixRem();
window.addEventListener("resize", function(){
fixRem();
});
function fixRem() {
var windowWidth = window.innderWidth || document.documentElement.clientWidth || document.body.clientWidth;
windowWidth = windowWidth < 320 ? 320 : windowWidth;
windowWidth = windowWidth > 750 ? 750 : windowWidth;
var rootSize = 20 * (windowWidth / 375);
var htmlNode = document.getElementsByTagName("html")[0];
htmlNode.style.fontSize = rootSize + 'px';
}
</script>
设计稿宽度:750px;
px计算rem:px/40 = rem
方式二:
<script>
(function(){
let html = document.documentElement;
let hWidth = html.getBoundingClientRect().width;
html.style.fontSize = hWidth / 15 + 'px';
})()
</script>
‘hWidth / 15’中的15可以理解为将屏幕横向平分16份
即:如果设计稿宽度为750px,则: 1rem = 50px
其中
(function(){})()
表示立即执行函数