移动端布局屏幕适配方案

  在移动端开发过程中,我们需要适配各种不同机型的屏幕,如何能够写一套代码适,做到屏幕的完美适配呢。针对设计稿为750*1334,自己常用的适配方案如下:

  • 方案一
    •  1 (function(doc, win){
       2       var docEl = doc.documentElement,
       3           resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
       4           recalc = function(){
       5               var clientWidth = docEl.clientWidth;
       6               if(!clientWidth) return;
       7               docEl.style.fontSize = 100 * (clientWidth / 750) + 'px';
       8           };
       9 
      10       if(!doc.addEventListener) return;
      11       win.addEventListener(resizeEvt, recalc, false);
      12       doc.addEventListener('DOMContentLoaded', recalc, false);
      13 })(document, window);

      对应的css

      1 .wrapper{
      2     padding: .2rem .3rem;//对应750的设计稿40px/60px
      3 }

       

  • 方案二
     1  var dpr, rem, scale;
     2   var docEl = document.documentElement;
     3   var fontEl = document.createElement('style');
     4   var metaEl = document.querySelector('meta[name="viewport"]');
     5   dpr = window.devicePixelRatio || 1;
     6   scale = 1 / dpr;
     7   rem = docEl.clientWidth * dpr / 10;
     8   metaEl.setAttribute('content', 'width=' + dpr * docEl.clientWidth + ',initial-scale=' + scale + ',maximum-scale=' + scale + ', minimum-scale=' + scale + ',user-scalable=no');
     9   docEl.setAttribute('data-dpr', dpr);
    10   docEl.firstElementChild.appendChild(fontEl);
    11   fontEl.innerHTML = 'html{font-size:' + rem + 'px!important;}';

     

  • 方案三
  •  1 @media (min-width: 320px){ // iphone4-5 >=375的设备
     2     html, body{
     3         font-size: 42.7px;
     4     }
     5 }
     6 @media (min-width: 340px){ // 主流设备
     7     html, body{
     8         font-size: 45.3px;
     9     }
    10 }
    11 @media (min-width: 360px){ // 主流设备
    12     html, body{
    13         font-size: 48px;
    14     }
    15 }
    16 @media (min-width: 375px){ // iphone6 >=375的设备
    17     html, body{
    18         font-size: 50px;
    19     }
    20 }
    21 @media (min-width: 400px){ // 主流设备
    22     html, body{
    23         font-size: 53.3px;
    24     }
    25 }
    26 @media (min-width: 414px){ // iphone6+ >=414的设备
    27     html, body{
    28         font-size: 55.2px;
    29     }
    30 }
    31 @media (min-width: 768px){ // >=768的设备
    32     html, body{
    33         font-size: 102.4px;
    34     }
    35 }
    36 @media (min-width: 992px){ // >=992的设备
    37     html, body{
    38         font-size: 132.7px;
    39     }
    40 }
    41 @media (min-width: 1200px){ // >=1200的设备
    42     html, body{
    43         font-size: 160px;
    44     }
    45 }
    46 body{
    47     font-size: .24rem; 
    48 }
    49 
    50 
    51 .wrapper{
    52       padding: .1rem .15rem;//对应750的设计稿10px/15px
    53     }

     

posted @ 2017-02-17 11:34  春眠不觉晓  阅读(343)  评论(0编辑  收藏  举报