移动端页面尺寸适配

以iphone6设计图为基准

做法一:

<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" />
    <style>
    body{
        margin: 0;
        padding: 0;
    }
    .box{
        width: 2rem; // 通过测量的尺寸除以100得到rem值
        height: 2rem;
        background: red;
    }
    </style>
</head>
<body>
    <div class="box"></div>
    <script>
    document.documentElement.style.fontSize = document.documentElement.clientWidth / 7.5 + 'px'; // 这个7.5是设计稿的宽度除以100得到的(如果以iphone5设计图为基准,7.5 => 6.4)
    </script>
</body>
</html>

做法二:

<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <meta name="viewport" content="" />
    <style>
    body{
        margin: 0;
        padding: 0;
    }
    .box{
        width: 2.66666667rem; // 通过测量的尺寸除以动态设置的html字体大小得到rem值(需要频繁使用计算器计算,影响开发效率)
        height: 2.66666667rem;
        background: red;
    }
    </style>
</head>
<body>
 
    <div class="box"></div>
 
    <script>
  // 通过设备像素比算出缩放比率
    var scale = 1 / window.devicePixelRatio;
 // 动态修改视口缩放比率   document.querySelector('meta[name="viewport"]').setAttribute('content','width=device-width,initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no');
 
    document.documentElement.style.fontSize = document.documentElement.clientWidth / 10 + 'px'; // 10是定死的一个值,这是和网易有很大的区别(不过网易没有动态修改视口缩放比率)
    </script>
</body>
</html>

两者页面元素尺寸都以rem为单位,但是文字字体大小不要使用rem换算,
而是使用媒体查询来进行动态设置,比如下面的代码就是网易的代码:

@media screen and (max-width: 321px) {
    body {
        font-size:16px
    }
}
 
@media screen and (min-width: 321px) and (max-width:400px) {
    body {
        font-size:17px
    }
}
 
@media screen and (min-width: 400px) {
    body {
        font-size:19px
    }
}

或者:

@media screen and (max-width: 321px) {
    header,footer {
        font-size:16px
    }
}
 
@media screen and (min-width: 321px) and (max-width:400px) {
    header,footer {
        font-size:17px
    }
}
 
@media screen and (min-width: 400px) {
    header,footer {
        font-size:19px
    }
}

 

posted @ 2020-05-08 14:59  Mr.渣、  阅读(904)  评论(0编辑  收藏  举报