要想移動(dòng)端適配 并使用 rem? 您需要先看這篇文章,配置好less ???在vue 中使用 less向抢,就可以使用rem了
如果項(xiàng)目已經(jīng)開(kāi)發(fā)的差不多了失尖,沒(méi)有用到rem 又要使用rem,您用這招辩蛋。
postcss-pxtorem:轉(zhuǎn)換px為rem的插件
安裝 postcss-pxtorem
npm install postcss-pxtorem --save
新建rem.js文件
const baseSize = 32
// 設(shè)置 rem 函數(shù)
functionsetRem () {
?// 當(dāng)前頁(yè)面寬度相對(duì)于 750 寬的縮放比例苹熏,可根據(jù)自己需要修改碟贾。
?const scale = document.documentElement.clientWidth / 750
?// 設(shè)置頁(yè)面根節(jié)點(diǎn)字體大小
?document.documentElement.style.fontSize = (baseSize * Math.min(scale, 2)) + 'px'
}
// 初始化
setRem()
// 改變窗口大小時(shí)重新設(shè)置 rem
window.onresize = function() {
?setRem()
}
并引用進(jìn)main.js文件內(nèi)
import './rem'
?修改.postcssrc.js 文件
在.postcssrc.js文件內(nèi)的 plugins 添加以下配置,配后就可以在開(kāi)發(fā)中直接使用 px 單位開(kāi)發(fā)了
"postcss-pxtorem": {
?????????"rootValue": 32,
?????????"propList": ["*"]
}
helloworld.vue
<template>
?<div class="hello">
?test
?</div>
</template>
<script>
?export default{
?name: 'HelloWorld',
?data() {
??return{
??msg: 'Welcome to Your Vue.js App'
??}
?}
?}
</script>
<style scoped>
?.hello {
?text-align: center;
?font-size: 20px;
?width: 300px;
?height: 400px;
?background:red;
?}
</style>
效果
此處已vue為例,在使用vue-cli搭建好項(xiàng)目框架后,在目錄結(jié)構(gòu)的index.html文件中添加一段js代碼:
fnResize();
? ? ? window.onresize = function () {
? ? ? ? fnResize();
? ? ? }
? ? ? function fnResize() {
? ? ? ? var deviceWidth = document.documentElement.clientWidth || window.innerWidth;
? ? ? ? if (deviceWidth >= 750) {
? ? ? ? ? deviceWidth = 750;
? ? ? ? }
? ? ? ? if (deviceWidth <= 320) {
? ? ? ? ? deviceWidth = 320;
? ? ? ? }
? ? ? ? document.documentElement.style.fontSize = (deviceWidth / 7.5) + 'px';
? ? ? }
然后在寫(xiě)css就可以將px單位換成rem.
這里設(shè)置的比例是100px=1rem,
例如:寬度為100px時(shí),可以直接寫(xiě)成1rem