<metaname="viewport"content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
代码一:
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";
}
代码二: 小米官网的写法
!function(n){
var e=n.document,
t=e.documentElement,
i=720,
d=i/100,
o="orientationchange"in n?"orientationchange":"resize",
a=function(){
var n=t.clientWidth||320;n>720&&(n=720);
t.style.fontSize=n/d+"px"
};
e.addEventListener&&(n.addEventListener(o,a,!1),e.addEventListener("DOMContentLoaded",a,!1))
}(window);
代码三:自适应代码
(function (win) {
var doc = win.document;
var docEl = doc.documentElement;
var tid;
function refreshRem() {
var width = docEl.getBoundingClientRect().width;
if (width > 750) { // 最大宽度
width = 750;
}
var rem = width / 3.75;
docEl.style.fontSize = rem + 'px';
}
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);
refreshRem();
})(window);
function htmlSize(){
var oHtml = document.documentElement;
var aWidth = oHtml.getBoundingClientRect().width;
if(aWidth < 750){
oHtml.style.fontSize = aWidth / 15 + "px";
}else{
oHtml.style.fontSize = 750 / 15 + "px";
}
}
(function(){
htmlSize();
})();
window.onresize = function(){
htmlSize();
}