Rem適配佈局(vue專案)
阿新 • • 發佈:2021-02-20
技術標籤:Vue
響應式:**postcss-plugin-px2rem(外掛)+postcss.config.js(檔案配置)+setRem.js(檔案配置)**方案使用
- npm i postcss-plugin-px2rem --save 下載安裝
- 建立檔案postcss.config.js並新增如下程式碼
// 一般postcss建議單獨配置在檔案postcss.config.js中
// var px2rem = require('postcss-px2rem');
module.exports = {
plugins: [
require('autoprefixer' )({
browsers: 'last 2 versions'
}),
require('postcss-plugin-px2rem')({
remUnit: 75
})
]
}
- 在vue.config.js中新增如下程式碼
lintOnSave: true,
css: {
loaderOptions: {
postcss: {
plugins: [
require('postcss-plugin-px2rem' )({
// rootValue: 100, //換算基數, 預設100 ,這樣的話把根標籤的字型規定為1rem為50px,這樣就可以從設計稿上量出多少個px直接在程式碼中寫多上px了。
// unitPrecision: 5, //允許REM單位增長到的十進位制數字。
//propWhiteList: [], //預設值是一個空陣列,這意味著禁用白名單並啟用所有屬性。
// propBlackList: [], //黑名單
exclude: /(node_module)/, //預設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
}),
]
}
}
},
- 在src目錄下新建 plugins資料夾,資料夾下新建setRem.js檔案,程式碼如下:
/**
* html根節點設定font-size
* @param {designwidth} Number 設計稿的寬度
*/
export const setRem = (designwidth) => {
function fontSizeFun() {
const fontSize = 100
const relwidth = document.documentElement.clientWidth
const relfontSize = fontSize * relwidth / designwidth + 'px'
document.getElementsByTagName('html')[0].style.fontSize = relfontSize
}
fontSizeFun()
window.onresize = fontSizeFun
}
- 在主入口main.js檔案下新增程式碼
import {
setRem
} from './plugins/setRem.js'
setRem('750')
//setRem('750') 代表設計稿的大小
// ./plugins/setRem.js 代表建立檔案時的路徑
效果圖:
在iPhone設計稿為750下根元素字型大小為50px