移动web端使用rem实现自适应原理

1.先获取到物理像素和实际像素的像素比

var pixclPatio = 1 / window.devicePixelRatio;

2.viewport视口设置为像素比大小

document.write('<meta name="viewport" content="width=device-width,initial-scale=' + pixclPatio + ',minimum-scale=' + pixclPatio + ',maximum-scale=' + pixclPatio + ',user-scalable=no" />');

3.根据屏幕宽度动态设置html的字体大小

var html = document.getElementsByTagName('html')[0];
var pageWidth = html.getBoundingClientRect().width;
html.style.fontSize = pageWidth / 50 + 'px';

4.在less或者sass中设置变量$rem或者@rem,然后将单位换成/@rem或/$rem就可以了。

@r: 15rem;

5.@rem: 15rem 的大小是根据设计图来决定的。这里我使用的是750的iphone6s的设计图,

因为html.style.fontSize = pageWidth / 50 + 'px';设置了在750的手机下面html的font-size:15px;所以想要让rem表示为一个像素。@rem需要设置为15rem
posted @ 2017-02-28 13:55  无情码字员  阅读(1408)  评论(0编辑  收藏  举报