npm install --save-dev postcss-plugin-px2rem
vue.config.js
module.exports = {css: {loaderOptions: {postcss: {plugins: [require('postcss-plugin-px2rem')({rootValue: 16, //換算基數, 默認100 ,1 / fontsize(html) = x 原來的1px轉為0.0625rem// unitPrecision: 5, //允許REM單位增長到的十進制數字。//propWhiteList: [], //默認值是一個空數組,這意味著禁用白名單并啟用所有屬性。// propBlackList: [], //黑名單// exclude: /(node_modules)/, //默認false,可以(reg)利用正則表達式排除某些文件夾的方法,例如/(node_module)/ 。如果想把前端UI框架內的px也轉換成rem,請把此屬性設為默認值// selectorBlackList: [], //要忽略并保留為px的選擇器// ignoreIdentifier: false, //(boolean/string)忽略單個屬性的方法,啟用ignoreidentifier后,replace將自動設置為true。// replace: true, // (布爾值)替換包含REM的規則,而不是添加回退。// mediaQuery: false, //(布爾值)允許在媒體查詢中轉換px。// minPixelValue: 3 //設置要替換的最小像素值(3px會被轉rem)。 默認 0//exclude: "/node_modules/",// selectorBlackList: ['html', 'mint-', 'mt-', 'mpvue-', 'calendar', 'iconfont'], //在rem.js全局作用下 排除指定的文件的影響// propBlackList: ['border']})]}}}
}
- 以上完成px->rem,為了某些已經以rem為單位的組件不受影響,如消息框圖標,這里將rootValue設置為html默認字體大小16px(html根字體大小代表rem代表的大小,此時1rem=16px)
- main.js中引入rem.js,監聽窗口變化,等比例改變根fontsize達到改變rem的大小
rem.js
// 設置 rem 函數
function setRem() {let htmlWidth = document.documentElement.clientWidth// let htmlHeight = document.documentElement.clientHeight//得到html的Dom元素let htmlDom = document.getElementsByTagName('html')[0];// //設置根元素字體大小 937 / 16 = 58.5625 , 937是谷歌1080 - 工具欄高度// htmlDom.style.fontSize = (htmlHeight / 58.5625) + 'px';//設置根元素字體大小 1920 / 16 = 120htmlDom.style.fontSize = (htmlWidth / 120) + 'px';
}
// 初始化
setRem();
// 改變窗口大小時重新設置 rem
window.onresize = function () {setRem()
}