rem布局适配方案的主要方法是:根据设计稿与设备宽度的比例,动态计算并设置html根标签的font-size;在css中,width,height,相对位置等值按比例转换为rem单位;设计稿中的字体以px为单位,通过mediaqueries稍作调整。1动态设置html标签的font-size大小精简通用版:!(function(win,doc){functionsetFontSize(){//获取窗口宽度//Zepto实现$(window).width()就是它的作用varwinWidth=window.innerWidth;//doc.documentElement.style.fontSize=(winWidth/640)*100+'px';//限制在640以上需要css配合varsize=(winWidth/640)*100;doc.documentElement.style.fontSize=(size<100?size:100)+'px';}varevt='onorientationchange'inwin?'orientationchange':'resize';vartimer=null;win.addEventListener(evt,function(){clearTimeout(timer);timer=setTimeout(setFontSize,300);},false);win.addEventListener("pageshow",function(e){if(e.persisted){clearTimeout(timer);timer=setTimeout(setFontSize,300);}},false);//初始化setFontSize();}(window,docume新));高端精准版:(function(WIN){varsetFontSize=WIN.setFontSize=function(_width){vardocEl=document.documentElement;//获取当前窗口的宽度varwidth=_width||docEl.clientWidth;//docEl.getBoundingClientRect().width;//大于1080px按1080if(width>1080){width=1080;}varrem=width/10;console.log(rem);docEl.style.fontSize=rem+'px';//错误和兼容性处理varactualSize=win.getComputedStyle&&parseFloat(win.getComputedStyle(docEl)["font-size"]);if(actualSize!==rem&&actualSize>0&&Math.abs(actualSize-rem)>1){varremScaled=rem*rem/actualSize;docEl.style.fontSize=remScaled+'px';}}vartimer;functiondbcRefresh(){clearTimeout(timer);timer=setTimeout(setFontSize,100);}//窗口更新动态改变font-sizeWIN.addEventListener('resize',dbcRefresh,false);//页面显示时计算一次WIN.addEventListener('pageshow',function(e){if(e.persisted){dbcRefresh()}},false);setFontSize();})(window)//H5活动推送页面,对宽高比有要求,可以适当调整functionadjustWarp(warpId='#warp'){const$win=$(窗户);constheight=$win.height();让宽度=$win.width();//考虑导航栏if(width/height600){return;}width=Math.ceil(height*360/640);$(warpId).css({height,width,position:'relative',top:0,left:'auto',margin:'0auto'});//重新计算remwindow.setFontSize(width);}2通过CSS3mediaQuery设置rem简单易用,缺乏灵活性,请看demo你知道@mediascreenand(min-width:320px){html{font-size:50px}}@mediascreenand(min-宽度:360px){html{font-size:56.25px}}@mediascreenand(min-width:375px){html{font-size:58.59375px}}@mediascreenand(min-width:384px){html{font-size:60px}}@mediascreenand(min-width:400px){html{font-size:62.5px}}@mediascreenand(min-width:414px){html{font-size:64.6875px}}@mediascreenand(min-width:424px){html{font-size:66.25px}}@mediascreenand(min-width:480px){html{font-size:75px}}@mediascreenand(min-width:540px){html{font-size:84.375px}}@mediascreenand(min-width:640px){html{font-size:100px}}可以根据个人项目需求和产品设计修改,以上演示写作不是唯一固定的。
