移动端调自适应的方法

 /**
一、 CSS中,无论是字号还是宽高,如果都使用rem单位,最终都是由根元素html的font-size大小决定的。 *
*/ function adaptFun(designPercent){ //移动端的body宽度(或者可用宽度,这个视情况定)为clientWidth //定义最大宽度mainWidth为body的宽度。 var mainWidth = document.body.clientWidth; //如果宽为640px,一般会设置html的font-size为20px var fontSize = mainWidth/designPercent + 'px'; document.documentElement.style.fontSize = fontSize; //视窗变化时,就要使用以下代码来重新适配。最主要的只是首次适配↑ window.onresize = function(){ var mainWidth = document.body.clientWidth; var fontSize = mainWidth/designPercent + 'px'; document.documentElement.style.fontSize = fontSize; } } //这里输出的是adaptFun(designPercent),因为designPercent=mainWidth/fontSize。 //一般会设置html的font-size为20px(移动端字号一般要除2)。 adaptFun(640/32); ========================================================================================================= /** 二、下面这段是京东的自适应定义 **/ (function() { var b = document.documentElement, a = function() { var a = b.getBoundingClientRect().width; b.style.fontSize = .0625 * (640 <= a ? 640 : a) + "px" }, c = null; window.addEventListener("resize", function() { clearTimeout(c); c = setTimeout(a, 300) }); a() })();

 

原文地址:https://www.cnblogs.com/raines/p/4594131.html