移動端佈局方案,簡單高效,完美適配各類機型

第一步:使用淘寶的lib/flexible+rem佈局css

原理:html

  rem佈局:使用rem做爲元素大小的單位,rem=fount-size,根據不一樣的屏幕寬度設置不一樣的fount-size值,這樣元素也會跟着屏幕變大或變小
vue

    lib/flexible:node

    經過js查詢屏幕大小,設置viewport標籤的同時始終將fount-size設置爲屏幕寬度的1/10。npm

    咱們也應該將設計稿分紅1/10與之對相應,json

    由此獲得1rem=屏幕寬度的1/10=設計稿的1/10app

    若是設計稿大小爲750px,則1rem=75px,
佈局

    好比在設計稿上量到一個寬度爲150的元素,能夠經過150/75獲得此元素在設備中的寬度爲2rempost

用法:flex

     去掉html中的viewport標籤,vue項目在public/index.html中操做

   vue項目中在main.js中引入flexible

   import ' lib/flexible/flexible.js '

引入後就實現了動態設置fount-size和viewport標籤了,接下來咱們只要在項目中以rem爲單位寫樣式就能夠了,可是每次都要手動計算rem太麻煩,可使用插件postcss-px2rem-exclude

 

第二步:使用postcss-px2rem-exclude將px轉換爲rem

    使用此插件後,它會將px按照咱們配置的比例來轉換成rem

用法:

  安裝:cnpm install postcss-px2rem-exclude -S

  配置:安裝插件後在package.json添加以下代碼

    "postcss": {

 

        "plugins": {

 

          "autoprefixer": {},

 

          "postcss-px2rem-exclude":{

 

              "remUnit": 75,              //你的設計稿的寬度的1/10爲多少px此處就填多少,通常設計稿爲750px

 

              "exclude":"/node_modules|floder_name/i"  //若是你使用了第三放ui庫,將它添加到此處,以避免衝突

 

          }

 

        }

 

      },
  使用:
    一、須要使用rem單位的直接寫px便可
    二、強制使用px爲單位如fount-size:
       font-size: 28px; /*px*/  編譯後會生成適應三種dpr的大小
      [data-dpr="1"] .selector {
        font-size: 14px;
      }
      [data-dpr="2"] .selector {
        font-size: 28px;
      }
      [data-dpr="3"] .selector {
        font-size: 42px;
      }
    三、不須要轉換的如1像素邊框: border: 1px solid #ddd; /*no*/
 
 
到此咱們就能夠按照設計稿的大小以px爲單位進行開發了,不過flexible不兼容ipad,因此咱們還要加一部
 
第三步:在html的head中加入適配ipad的script標籤
     直接賦值粘貼就行

<script>
/(iPhone|iPad|iPhone OS|Phone|iPod|iOS)/i.test(navigator.userAgent)&&(head=document.getElementsByTagName('head'),viewport=document.createElement('meta'),viewport.name='viewport',viewport.content='target-densitydpi=device-dpi, width=480px, user-scalable=no',head.length>0&&head[head.length-1].appendChild(viewport));
</script>

這樣下來幾乎全部的移動端都能適配了

相關文章
相關標籤/搜索