当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue使用rem实现 移动端屏幕适配

vue使用rem实现 移动端屏幕适配

2019年06月02日  | 移动技术网IT编程  | 我要评论
要想移动端适配 并使用 rem  您需要先看这篇文章,配置好less ➡️ ,就可以使用rem了 如果项目已经开发的差不多了,没有用

要想移动端适配 并使用 rem  您需要先看这篇文章,配置好less ➡️ ,就可以使用rem了

如果项目已经开发的差不多了,没有用到rem 又要使用rem,您用这招。

postcss-pxtorem:转换px为rem的插件

安装 postcss-pxtorem

npm install postcss-pxtorem --save

 

新建rem.js文件

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文件内

import './rem'

 修改.postcssrc.js 文件

在.postcssrc.js文件内的 plugins 添加以下配置,配后就可以在开发中直接使用 px 单位开发了

 "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用rem布局

使用vue.js搭建一个移动端项目,怎样做到自适应呢?当然选择rem布局是比较方便快捷的。

在使用vue-cli搭建好项目框架后,在目录结构的文件中添加一段代码:

<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。

总结

以上所述是小编给大家介绍的vue使用rem实现 移动端屏幕适配 ,希望对大家有所帮助

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网