Rem.js

作者: 苦咖啡Li | 来源:发表于2019-12-21 16:25 被阅读0次
    750 代表设计稿的宽度;
    100 代表换算比例,写100是 为了好计算;比如,一个元素的宽度是100px,就可以写1rem,以及1px=0.01rem
        // rem 前端自适应代码
        (function (win) {
            let doc = win.document, docEl = doc.documentElement, timer = null;
            function refreshRem() {
              //  ele.getBoundingClientRect()    返回元素的大小及其相对于视口的位置。
              
                let width = docEl.getBoundingClientRect().width;    
                if (width > 750) { // 最大宽度,  750为设计稿的宽度
                    docEl.style.fontSize =  '100px';
                }else{
                    var rem = width / 3.75;
                    docEl.style.fontSize = rem + 'px';
                }
            }
            
            win.addEventListener('resize', function () {
                clearTimeout(tid);
                timer = setTimeout( refreshRem , 300);
            }, false);
            
            win.addEventListener('pageshow', function (e) {
              //  e.persisted  判断是否后退进入
              
                if (e.persisted) {
                    clearTimeout(tid);
                    timer = setTimeout(refreshRem, 300);
                }
            }, false);
            
            refreshRem();
            
        })(window);
    

    相关文章

      网友评论

          本文标题:Rem.js

          本文链接:https://www.haomeiwen.com/subject/gbwbnctx.html