话很少说直接上代码css
window.onload = function(){
/*720表明设计师给的设计稿的宽度,你的设计稿是多少,就写多少;100表明换算比例,这里写100是 为了之后好算,好比,你测量的一个宽度是100px,就能够写为1rem,以及1px=0.01rem等等*/
getRem(720,100)
};
window.onresize = function(){
getRem(720,100)
};
function getRem(pwidth,prem){
var html = document.getElementsByTagName("html")[0];
var oWidth = document.body.clientWidth || document.documentElement.clientWidth;
html.style.fontSize = oWidth/pwidth*prem + "px";
}
复制代码
看这两个函数,把这些代码放到js里面,规则就是,调用函数,放两个参数,第一个参数,是设计稿的宽度,第二个参数是px与rem的转换比例,一般会写100(由于好算);固然了,要把这段js代码最好封装在一个单独的js文件里,而且放在全部的css文件引入以前加载。 实际应用起来就是,#box1{ height:100px;}而调用了rem就是#box1{ height:1rem;}以此类推。 100px = 1rem . 1px = 0.01rem。在页面中,凡是跟尺寸有关的padding、margin、width、height等等,均可以用rem来写单位,这样当不一样分辨率的手机在看同一个页面时,效果几乎是同样的html
designWidth
:设计稿的实际宽度值,须要根据实际设置
maxWidth
:制做稿的最大宽度值,须要根据实际设置浏览器
这段js的最后面有两个参数记得要设置,一个为设计稿实际宽度,一个为制做稿最大宽度,例如设计稿为750,最大宽度为750,则为(750,750)app
;(function(designWidth, maxWidth) {
var doc = document,
win = window,
docEl = doc.documentElement,
remStyle = document.createElement("style"),
tid;
function refreshRem() {
var width = docEl.getBoundingClientRect().width;
maxWidth = maxWidth || 540;
width>maxWidth && (width=maxWidth);
var rem = width * 100 / designWidth;
remStyle.innerHTML = 'html{font-size:' + rem + 'px;}';
}
if (docEl.firstElementChild) {
docEl.firstElementChild.appendChild(remStyle);
} else {
var wrap = doc.createElement("div");
wrap.appendChild(remStyle);
doc.write(wrap.innerHTML);
wrap = null;
}
//要等 wiewport 设置好后才能执行 refreshRem,否则 refreshRem 会执行2次;
refreshRem();
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 = "16px";
} else {
doc.addEventListener("DOMContentLoaded", function(e) {
doc.body.style.fontSize = "16px";
}, false);
}
})(750, 750);
复制代码
部分写法:函数
html {
font-size : 20px;
}
@media only screen and (min-width: 401px){
html {
font-size: 25px !important;
}
}
@media only screen and (min-width: 428px){
html {
font-size: 26.75px !important;
}
}
@media only screen and (min-width: 481px){
html {
font-size: 30px !important;
}
}
@media only screen and (min-width: 569px){
html {
font-size: 35px !important;
}
}
@media only screen and (min-width: 641px){
html {
font-size: 40px !important;
}
}
复制代码