当前位置: 首页 > Web前端 > HTML

H5页面rem布局适配方法

时间:2023-04-02 20:10:01 HTML

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/height