vue項目px自動轉成rem適配


如果是做 PC 端的網頁,無需做 rem 適配,但是做 H5 開發,rem 是需要做一下的

方案一:

Vant 官方也為我們提供了方案,如下圖所示:

 

 

 

 咱們就按照官方為我們提供的方案進行適配,安裝它們:

yarn add lib-flexible -S
yarn add postcss-pxtorem -D
1 //這里 lib-flexible 是網頁做 html 的 font-size 適配用的,所以需要安裝到 
2 <br/>//dependencies。而 postcss-pxtorem 是在編譯的時候對 px 單位轉
3 <br/>//換為 rem 單位時使用,所以安裝到 devDependencies 便可。

安裝好后,我們需要在 main.js 引入 lib-flexible,新增如下代碼:

import { createApp } from 'vue'
import { Button } from 'vant';
import 'lib-flexible/flexible'
import App from './App.vue'
import router from './router'
import 'vant/lib/index.css'; // 全局引入樣式
import './index.css'

const app = createApp(App) // 創建實例

app.use(Button) // 注冊組件
app.use(router)

app.mount('#app')

接着我們需要為 px 單位轉 rem 單位做配置。

起初我犯了一個錯誤,在根目錄聲明 .postcssrc.js 文件,但是目前 Vite 創建的項目已經不支持這種形式的配置文件了,而是需要 postcss.config.js 文件,配置內容如下:

// postcss.config.js // 用 vite 創建項目,配置 postcss 需要使用 post.config.js,之前使用的 .postcssrc.js 已經被拋棄 // 具體配置可以去 postcss-pxtorem 倉庫看看文檔 module.exports = { "plugins": { "postcss-pxtorem": { rootValue: 37.5, // Vant 官方根字體大小是 37.5 propList: ['*'], selectorBlackList: ['.norem'] // 過濾掉.norem-開頭的class,不進行rem轉換 } } }


這里還有一個需要注意的小知識點:不需要 px 轉 rem 的情況,可以使用大寫的 PX 作為單位。

編譯時不會將其轉化為 rem 單位,也可以通過 selectorBlackList 屬性聲明的 .norem 前綴的 class 類名,同樣也不會被轉化。

方案二:
 //第一種寫法需要除以100;
        window.onload = function(){
            getRem(375,100)
        };
        window.onresize = function(){
            getRem(375,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";
        }
 
         
//小米官網的寫法
        !function(n){
            var  e=n.document,
                 t=e.documentElement,
                 i=720,
                 d=i/100,
                 o="orientationchange"in n?"orientationchange":"resize",
                 a=function(){
                     var n=t.clientWidth||320;n>720&&(n=720);
                     t.style.fontSize=n/d+"px"
                 };
                 e.addEventListener&&(n.addEventListener(o,a,!1),e.addEventListener("DOMContentLoaded",a,!1))
        }(window);
 
方案三:
引入
 "postcss-px2rem": "^0.3.0",
    "px2rem-loader": "^0.1.9",

1.安裝

npm i postcss-px2rem --save -dev

2.設置

1).找到項目根目錄下的.postcssrc文件

module.exports = {
  "plugins": {
    "postcss-import": {},
    "postcss-url": {},
    // to edit target browsers: use "browserslist" field in package.json
    "autoprefixer": {
      "browsers": ['last 10 Chrome versions', 'last 5 Firefox versions', 'Safari >= 8']
     },
     'postcss-px2rem':{'remUnit':75}    //配置rem基准值,75是iphone6標准
  }
}

remUnit: 75 代表 1rem = 75px; 所以當你一個75px值時,它會自動轉成 (75px/75)rem,

轉化完之后,你還需要在根元素設置他的font-size,因為rem是相對根元素來設置大小的

html {
    font-size: 10vw;
}

這樣的話我們設置的px值 就變成對應的 10%的屏幕寬度 *(75px/75)rem

2) 找到根目錄下的vue-loader.conf.js

本人使用的是這種方法.
首先需要設置html的fontsize值,1rem = html的font-size,這里咱們動態設置一下,可以直接在index.html中設置
PC端

 1 (function () {
 2     function setRootFontSize() {
 3         let rem, rootWidth;
 4         let rootHtml = document.documentElement;
 5         //限制展現頁面的最小寬度
 6         rootWidth = rootHtml.clientWidth < 1366 ? 1366 : rootHtml.clientWidth;
 7         // 19.2 = 設計圖尺寸寬 / 100( 設計圖的rem = 100 )
 8         rem = rootWidth / 19.2;
 9         // 動態寫入樣式
10         rootHtml.style.fontSize = `${rem}px`;
11     }
12     setRootFontSize();
13     window.addEventListener("resize", setRootFontSize, false);
14 })();

移動端

(function () {
    function setRootFontSize() {
        let dpr, rem, scale, rootWidth;
        let rootHtml = document.documentElement;
    
        dpr = window.devicePixelRatio || 1; //移動端必須設置
        //限制展現頁面的最小寬度
        rootWidth = rootHtml.clientWidth < 1366 ? 1366 : rootHtml.clientWidth;
        rem = rootWidth * dpr / 19.2; // 19.2 = 設計圖尺寸寬1920 / 100(設計圖的rem = 100)
        scale = 1 / dpr;
    
        // 設置viewport,進行縮放,達到高清效果 (移動端添加)
        let vp = document.querySelector('meta[name="viewport"]');
        vp.setAttribute('content', 'width=' + dpr * rootHtml.clientWidth + ',initial-scale=' + scale + ',maximum-scale=' + scale + ', minimum-scale=' + scale + ',user-scalable=no');
    
        // 動態寫入樣式
        rootHtml.style.fontSize = `${rem}px`;
    }
    setRootFontSize();
    window.addEventListener("resize", setRootFontSize, false);
    window.addEventListener("orientationchange", setRootFontSize, false); //移動端
})();

 

 

'use strict'
const utils = require('./utils')
const config = require('../config')
const isProduction = process.env.NODE_ENV === 'production'
const sourceMapEnabled = isProduction
  ? config.build.productionSourceMap
  : config.dev.cssSourceMap

const px2rem = require('postcss-px2rem')
module.exports = {
  loaders: utils.cssLoaders({
    sourceMap: sourceMapEnabled,
    extract: isProduction
  }),
  cssSourceMap: sourceMapEnabled,
  cacheBusting: config.dev.cacheBusting,
  transformToRequire: {
    video: ['src', 'poster'],
    source: 'src',
    img: 'src',
    image: 'xlink:href'
  },
  postcss: function() {
    return [px2rem({remUnit: 100})];
  }
}

 

 // 淘寶用法

 

 

   

 

 

      document.getElementsByTagName('html')[0].style.fontSize = (document.documentElement.clientWidth ||  document.body.clientWidth) /10 + 'px';

 

 如果想要rem為小數,基數可以取整

public/index.html下

 1 <script>
 2     const baseSize = 100 // 基准值
 3     function setRem() {
 4       // 相對於1920像素的縮放比
 5       let scale = document.documentElement.clientWidth / 1920
 6       // 根據屏幕變化 1rem 對應的 font-size
 7       scale = scale > 1 ? 1 : scale;
 8       const realFont = baseSize * scale
 9       document.documentElement.style.fontSize = realFont + 'px'
10     }
11     setRem()
12     window.onresize = () => {
13       setRem()
14     }
15 </script>

下載 postcss-px2rem

npm install postcss-px2rem -D

在vue.config.js中配置

 
         
 1 const px2rem = require('postcss-px2rem')
 2 
 3 const postcss = px2rem({
 4   remUnit: 100 // 基准值
 5 })
 6 
 7 module.exports = {
 8   publicPath: './',
 9   css: {
10     loaderOptions: {
11       postcss: {
12         plugins: [
13           postcss
14         ]
15       }
16     }
17   }
18 }
 
         

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM