Rem实现自适应

① 通过media query设置

统计自己网站有哪些主流的屏幕设备,然后去针对那些设备去做media query设置也可以实现适配

html {
    font-size : 20px;
}
@media only screen and (min- 401px){
    html {
        font-size: 25px !important;
    }
}
@media only screen and (min- 428px){
    html {
        font-size: 26.75px !important;
    }
}
@media only screen and (min- 481px){
    html {
        font-size: 30px !important; 
    }
}
@media only screen and (min- 569px){
    html {
        font-size: 35px !important; 
    }
}
@media only screen and (min- 641px){
    html {
        font-size: 40px !important; 
    }
}

不足之处

不能所有设备全适配,但是用JS是可以实现全适配。具体用哪个就要根据自己的实际工作场景去定了。

Rem自适应js,使用flexible.js

flexible.js 的用法非常的简单,在页面的<head></head>中引入 flexible_css.js,flexible.js文件:

<script src="http://g.tbcdn.cn/mtb/lib-flexible/0.3.4/??flexible_css.js,flexible.js"></script>

.css 文件内容:

@charset "utf-8";
html{color:#000;background:#fff;overflow-y:scroll;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}
html *{outline:0;-webkit-text-size-adjust:none;-webkit-tap-highlight-color:rgba(0,0,0,0)}
html,body{font-family:sans-serif}
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td,hr,button,article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{margin:0;padding:0}
input,select,textarea{font-size:100%}
table{border-collapse:collapse;border-spacing:0}
fieldset,img{border:0}
abbr,acronym{border:0;font-variant:normal}
del{text-decoration:line-through}address,caption,cite,code,dfn,em,th,var{font-style:normal;font-weight:500}
ol,ul{list-style:none}
caption,th{text-align:left}
h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:500}
q:before,q:after{content:''}
sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}
sup{top:-.5em}
sub{bottom:-.25em}
a:hover{text-decoration:underline}
ins,a{text-decoration:none}

.js 文件内容:

(function(win, lib) {
    var doc = win.document;
    var docEl = doc.documentElement;
    var metaEl = doc.querySelector('meta[name="viewport"]');
    var flexibleEl = doc.querySelector('meta[name="flexible"]');
    var dpr = 0;
    var scale = 0;
    var tid;
    var flexible = lib.flexible || (lib.flexible = {});
     
    if (metaEl) {
        console.warn('将根据已有的meta标签来设置缩放比例');
        var match = metaEl.getAttribute('content').match(/initial-scale=([d.]+)/);
        if (match) {
            scale = parseFloat(match[1]);
            dpr = parseInt(1 / scale);
        }
    } else if (flexibleEl) {
        var content = flexibleEl.getAttribute('content');
        if (content) {
            var initialDpr = content.match(/initial-dpr=([d.]+)/);
            var maximumDpr = content.match(/maximum-dpr=([d.]+)/);
            if (initialDpr) {
                dpr = parseFloat(initialDpr[1]);
                scale = parseFloat((1 / dpr).toFixed(2));   
            }
            if (maximumDpr) {
                dpr = parseFloat(maximumDpr[1]);
                scale = parseFloat((1 / dpr).toFixed(2));   
            }
        }
    }
    if (!dpr && !scale) {
        var isAndroid = win.navigator.appVersion.match(/android/gi);
        var isIPhone = win.navigator.appVersion.match(/iphone/gi);
        var devicePixelRatio = win.devicePixelRatio;
        if (isIPhone) {
            // iOS下,对于2和3的屏,用2倍的方案,其余的用1倍方案
            if (devicePixelRatio >= 3 && (!dpr || dpr >= 3)) {               
                dpr = 3;
            } else if (devicePixelRatio >= 2 && (!dpr || dpr >= 2)){
                dpr = 2;
            } else {
                dpr = 1;
            }
        } else {
            // 其他设备下,仍旧使用1倍的方案
            dpr = 1;
        }
        scale = 1 / dpr;
    }
    docEl.setAttribute('data-dpr', dpr);
    if (!metaEl) {
        metaEl = doc.createElement('meta');
        metaEl.setAttribute('name', 'viewport');
        metaEl.setAttribute('content', 'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no');
        if (docEl.firstElementChild) {
            docEl.firstElementChild.appendChild(metaEl);
        } else {
            var wrap = doc.createElement('div');
            wrap.appendChild(metaEl);
            doc.write(wrap.innerHTML);
        }
    }
    function refreshRem(){
        var width = docEl.getBoundingClientRect().width;
        if (width / dpr > 540) {
            width = 540 * dpr;
        }
        var rem = width / 10;
        docEl.style.fontSize = rem + 'px';
        flexible.rem = win.rem = rem;
    }
    win.addEventListener('resize', function() {
        clearTimeout(tid);
        tid = setTimeout(refreshRem, 300);
    }, false);
    win.addEventListener('pageshow', function(e) {
        if (e.persisted) {
            clearTimeout(tid);
            tid = setTimeout(refreshRem, 300);
        }
    }, false);
    if (doc.readyState === 'complete') {
        doc.body.style.fontSize = 12 * dpr + 'px';
    } else {
        doc.addEventListener('DOMContentLoaded', function(e) {
            doc.body.style.fontSize = 12 * dpr + 'px';
        }, false);
    }
     
    refreshRem();
    flexible.dpr = win.dpr = dpr;
    flexible.refreshRem = refreshRem;
    flexible.rem2px = function(d) {
        var val = parseFloat(d) * this.rem;
        if (typeof d === 'string' && d.match(/rem$/)) {
            val += 'px';
        }
        return val;
    }
    flexible.px2rem = function(d) {
        var val = parseFloat(d) / this.rem;
        if (typeof d === 'string' && d.match(/px$/)) {
            val += 'rem';
        }
        return val;
    }
})(window, window['lib'] || (window['lib'] = {}));

flexible.js 做了下面三件事:

  • 动态改写标签
  • 给<html>元素添加data-dpr属性,并且动态改写data-dpr的值
  • 给<html>元素添加font-size属性,并且动态改写font-size的值

详解

假设做一个页面(设计稿宽为 750px),Flexible会将视觉稿分成**100份**(主要为了以后能更好的兼容vh和vw),而每一份被称为一个单位a。同时1rem单位被认定为10a。针对我们这份视觉稿可以计算出:

换算
  1. 1a = 7.5px
  2. 1rem = 10a
  3. 1rem = 75px

上面这一小段可以说是 flexible.js 的精华所在了。但你只需要记住1rem = 75px 就好。比如上面云库网这个 LOGO 距离左边60px,上边42px,图片自身宽、高都是80px。当然你也可以直接用这些数值:

传统做法
.logo{
80px;
height:80px;
margin-left:60px;
margin-top:42px;
}

但我们是要在移动端做适配的,这样写还有什么适配可言?我们可以把上面的像素转换成 rem。rem 是根据根元素(html 的字体大小)来进行计算的,这样就可以很方便地让我们把设计稿等比缩放到与实践终端相匹配的大小。

移动适配
.logo{
 1.066667rem;
height: 1.066667rem;
margin-left: 0.8rem;
margin-top: 0.56rem;
}

说得简单点就是 rem 相当于我们平常用的百分比,只不过 rem 是相对根元素的。而我们的根元素是根据终端屏幕大小来动态设置的,所以不管是 iphone 6 plus (尺寸为414*736)还是 iphone 6 (尺寸为375*667),或者是其它任何终端设备都可以很完美地还原设计稿。

原文地址:https://www.cnblogs.com/maogu2/p/14485543.html