安裝postcss-px2rem插件,目的:把px轉(zhuǎn)變?yōu)閞em
npm install postcss-px2rem -S
vue.config.js中配置remUnit
const port = process.env.port || 8081 // 端口
module.exports = {
devServer: {
host: '0.0.0.0',
port: port,
open: true,
},
css: {
loaderOptions: {
css: {},
postcss: {
plugins: [
require('postcss-px2rem')({
remUnit: 100
})
]
}
}
}
}
一直不太明白為什么remUnit設(shè)置為100,通過項目中不斷的改變remUnit值,
發(fā)現(xiàn)這里remUnit值是為了把px轉(zhuǎn)換成rem的計算值,
即remUnit=100,
則1rem=100px,1px=0.01rem
當(dāng)項目中我們在css樣式中設(shè)置width:750px時,經(jīng)過[postcss-px2rem]這個插件轉(zhuǎn)換
remStyle:轉(zhuǎn)換后的值(單位:rem)
pxStyle:轉(zhuǎn)換前的值(單位:px)
remStyle=(pxStyle/remUnit)+'rem'
得到:width:7.5rem
通過js改變html的fontsize值
<script type="text/javascript">
function getHtmlFontSize() {
//獲取設(shè)備寬度
let deviceWidth = document.documentElement.clientWidth || window.innerWidth;
console.log("[設(shè)備寬度]", deviceWidth);
if (deviceWidth >= 750) {
deviceWidth = 750;
} else if (deviceWidth <= 320) {
deviceWidth = 320;
}
//設(shè)置html的字體大小為:1rem=100px;以設(shè)計原型750,如果設(shè)計稿是640px,font-size=100px,則為deviceWidth/6.4
document.documentElement.style.fontSize = (deviceWidth / 7.5) + 'px';
}
getHtmlFontSize();
window.addEventListener("resize", getHtmlFontSize)
</script>
postcss-px2rem插件不能把行內(nèi)樣式進(jìn)行pxTorem的轉(zhuǎn)換
文章來源地址http://www.zghlxwxcb.cn/news/detail-600341.html
文章來源:http://www.zghlxwxcb.cn/news/detail-600341.html
到了這里,關(guān)于在vue項目中使用postcss-px2rem插件把px轉(zhuǎn)變?yōu)閞em,并配合給html根元素設(shè)置fontsize,來實現(xiàn)頁面的自適應(yīng)效果的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!