移动前端开发rem CSS和JS的动态适配 - 戴向天

大家好!我叫戴向天

QQ群:602504799

QQ:809002582

CSS 如下

@charset "UTF-8";
html{font-size: 100px;}
@media screen and (min-width:320px){html{font-size:42.667px;}}
@media screen and (min-width:360px){html{font-size:48px;}}
@media screen and (min-width:375PX){html{font-size:50px;}}
@media screen and (min-width:384px){html{font-size:51.2px;}}
@media screen and (min-width:400px){html{font-size:53.3px;}}
@media screen and (min-width:412px){html{font-size:54.9px;}}
@media screen and (min-width:414px){html{font-size:55.2px;}}
@media screen and (min-width:424px){html{font-size:56.5px;}}
@media screen and (min-width:480px){html{font-size:64px;}}
@media screen and (min-width:540px){html{font-size:72px;}}
@media screen and (min-width:720px){html{font-size:96px;}}
@media screen and (min-width:750px){html{font-size:100px;}}
@media screen and (min-width:768px){html{font-size: 102.4px;}}
@media screen and (min-width:800px){html{font-size: 106.7px;}}
@media screen and (min-width:980px){html{font-size: 130.7px;}}
@media screen and (min-width:1080px){html{font-size: 144px;}}
@media screen and (min-width:1152px){html{font-size: 153.6px;}}
@media screen and (min-width:1366px){html{font-size: 182.1px;}}
@media screen and (min-width:1440px){html{font-size: 192px;}}
@media screen and (min-width:2160px){html{font-size: 288px;}}

JS 如下

window.onload = function(){
    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";
}

个人建议使用CSS方式进行适配,因为当我在使用H5开发APP的时候,发现使用JS来自适应的方式它有延迟,例如:当页面开始加载的时候 ,获取某个元素的高度时,JS方式的自适应还没有加载过来,获取的高度并不是真实的高度。JS自适应的它是需要window加载完毕之后才执行。所以有点延迟。
当然也可以根据需要来选择是CSS和JS

猜你喜欢

转载自blog.csdn.net/weixin_41088946/article/details/101107675