vue使用postcss-pxtorem实现自适应

安装:

npm install  postcss-pxtorem  -D

vue.config.js文件设置:

  css: {
    loaderOptions: {
      scss: {
        additionalData: `@import "~element-ui/packages/theme-chalk/src/common/var.scss";@import"@/styles/variables.scss";`
      },
      postcss: {
        postcssOptions: {
          plugins: [
            require("postcss-pxtorem")({
              // 配置文档:https://www.npmjs.com/package/postcss-pxtorem
              rootValue: 16, // 根元素字体大小 16/1.25
              unitPrecision: 5, // 转换成rem后保留的小数点位数
              propList: ["*"], // 匹配CSS中的属性,* 代表启用所有属性
              // exclude: /(node_module)/, // 忽略一些文件,不进行转换,默认false,可以(reg)利用正则表达式排除某些文件夹的              方法,例如/(node_module)/ 。如果想把前端UI框架内的px也转换成rem,请把此属性设为默认值
              mediaQuery: false, //(布尔值)允许在媒体查询中转换px
              minPixelValue: 1, // 设置要替换的最小像素值
            }),
          ],
        },
      },
    }
  },

创建一个js文件,引入main.js文件

// 基准大小
const baseSize = 16;
// 设置 rem 函数
function setRem() {
  // 当前页面宽度相对于 1920 宽的缩放比例,可根据自己需要修改。
  const scale = document.documentElement.clientWidth / 1920;
  // 设置页面根节点字体大小,设置个最小值,避免字体太小
  let fontSize = Math.max(baseSize * Math.min(scale, 2) ,12) 
  document.documentElement.style.fontSize = fontSize+"px";
}
// 初始化
setRem();
// 改变窗口大小时重新设置 rem
window.onresize = function () {
  setRem();
};

在实际开发中,echarts组件也需要根据实际进行字体转换,在utils.js文件中创建方法

export function fontSize(res) {
   let clientWidth =
      window.innerWidth ||
      document.documentElement.clientWidth ||
      document.body.clientWidth;
  if (!clientWidth) return;
  // 此处的1920 为设计稿的宽度,记得修改!
  let fontSize = clientWidth / 1920;
  return res * fontSize;
}

使用,例如:

import {fontSize} from "@/utils/index.js"

  legend: {
          itemWidth: 6,
          itemGap: 20,
          x: "left",
          y: "top",
          textStyle: {
            fontSize: fontSize(14),
            color: "#666666",
          },
        },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值