vue使用rem實現 移動端屏幕適配

要想移動端適配 並使用 rem  您須要先看這篇文章,配置好less ➡️ 在vue 中使用 less,就能夠使用rem了css

若是項目已經開發的差很少了,沒有用到rem 又要使用rem,您用這招。html

postcss-pxtorem:轉換px爲rem的插件前端

安裝 postcss-pxtoremvue

前端精品教程:百度網盤下載vue-cli

npm install postcss-pxtorem --savenpm

 

新建rem.js文件框架

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const baseSize = 32
// 設置 rem 函數
function setRem () {
  // 當前頁面寬度相對於 750 寬的縮放比例,可根據本身須要修改。
  const scale = document.documentElement.clientWidth / 750
  // 設置頁面根節點字體大小
  document.documentElement.style.fontSize = (baseSize * Math.min(scale, 2)) + 'px'
}
// 初始化
setRem()
// 改變窗口大小時從新設置 rem
window.onresize = function () {
  setRem()
}

並引用進main.js文件內less

import './rem'函數

 修改.postcssrc.js 文件佈局

前端精品教程:百度網盤下載

在.postcssrc.js文件內的 plugins 添加如下配置,配後就能夠在開發中直接使用 px 單位開發了

?
1
2
3
4
"postcss-pxtorem" : {
  "rootValue" : 32,
  "propList" : [ "*" ]
}

helloworld.vue

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<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用rem佈局

前端精品教程:百度網盤下載

使用vue.js搭建一個移動端項目,怎樣作到自適應呢?固然選擇rem佈局是比較方便快捷的。

在使用vue-cli搭建好項目框架後,在目錄結構的index.html文件中添加一段代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script>
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'
}
</script>

以後,在寫css時,只要將px單位替換成rem,這裏設置的比例是100px=1rem,例如,寬度爲100px時,能夠直接寫成1rem。

相關文章
相關標籤/搜索