解决移动端适配的方法

366 阅读2分钟

1、viewport适配

即通过设置initial-scale,将所有设备布局视口的宽度调整为设计时的宽度。

//获取meta节点
var meta = document.querySelector('meta[name=viewport]');
//定义设计宽度
var designWidth = 375;
//计算显示屏幕与设计宽度比例
var scale = document.documentElement.clientWidth/designWidth;
//设置meta中content的initial-scale
meta.content = "initial-scale =" + scale +",+ minimum-scale = " + scale + ", + maximum-scale =" + scale + ", user-scalable = no"

2、media适配

借助rem,当屏幕尺寸改变时,修改html元素的font-size

@media screen and (min-width:320px){html{font-size:50px}}; //iphone5/SE
@media screen and (min-width:360px){html{font-size:56.25px}}; 
@media screen and (min-width:375px){html{font-size:58.59375px}};//iphone6/7/8
@media screen and (min-width:400px){html{font-size:62.5px}};
@media screen and (min-width:414px){html{font-size:64.6875px}}; //iphone6/7/8plus
@media screen and (min-width:440px){html{font-size:68.75px}};
@media screen and (min-width:480px){html{font-size:75px}};
@media screen and (min-width:520px){html{font-size:81.25px}};
@media screen and (min-width:600px){html{font-size:93.75px}};
@media screen and (min-width:640px){html{font-size:100px}};
@media screen and (min-width:680px){html{font-size:106.25px}};
@media screen and (min-width:720px){html{font-size:112.5px}};
@media screen and (min-width:760px){html{font-size:118.75px}};
@media screen and (min-width:800px){html{font-size:125px}};
@media screen and (min-width:960px){html{font-size:150px}};

这里是常用的一些,有其他需要自行添加

3、js动态修改+less

//获取当前屏幕宽度
var screen = document.documentElement.clientWidth;
//计算对应字体大小
var size = screen/16;
//设置根元素字体
document.documentElement.style.fontSize = size + 'px';

将设计时宽度配合less定义一个rem,

@rem = designWidth/16;
//在less中即可
div{
   width:200/@rem;
   hight:200/@rem;
}

同理也可以使用js进行获取,而不用在less中

//获取当前屏幕宽度
var screen = document.documentElement.clientWidth;
//设置根元素字体
document.documentElement.style.fontSize = screen + 'px';
/** ========================================== */
//在js中获取查找
div{
   width:200/designWidth rem;
   hight:200/designHeight rem;
}

4、js计算比例+rem

//设计宽度 例375
var designWidth = 375;
//设置对应的字图大小, 例50
var rempx = 50
//获取当前屏幕宽度
var nowWidth = window.innerWidth
//获取对应比例
var scale = nowWidth/designWidth;
//动态计算根元素字体大小
document.documentElement.style.fontSize = scale * rempx + 'px'