写一个js配合rem

rem.js

目前笔者解决移动端的尺寸带来的样式问题,都是通过viewport + rem的。viewport 相信大家都用过了,而rem需要用js动态设置html的字体大小。

动态设置rem的根字体大小

  1. 首先我们要确定你的设计稿大小是多少,一般移动端设计稿的宽度是750,当然也用些用1080的;
  2. 我们要确定rem和px的转换比例,前提是要注意浏览器的字体大小是有限制的,比如chrome的字体不能小于12px;
  3. 记得加上viewport,比如这样设置:<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">;
/**
* design: 是设计稿的宽度,也是页面的最大宽度
* 这里的比例是1:100; 1rem = 100px;
**/
function setRem(design=750){
    let styleElm = document.createElement('style');
    rem();
    document.firstElementChild.appendChild(styleElm);
    window.onresize = function(){
        rem();
    }
    
    function rem(){
        let winWidth = document.documentElement.getBoundingClientRect().width;
        winWidth = Math.min(winWidth,design);
        let fontSize = winWidth / design *100;
        document.body.style.fontSize = '16px';
        styleElm.innerHTML = 'html {font-size:'+fontSize+'px;}';
    }
}

猜你喜欢

转载自www.cnblogs.com/blogs-xlf/p/11994418.html