vuejs - - - - - 移动端设备兼容(pxtorem)

pxtorem的使用

  • 1. 依赖安装
  • 2. vue.config.js配置
  • 3. 动态设置html的font-size大小
  • 4. 效果如图:

1. 依赖安装

yarn add postcss-pxtorem -D

2. vue.config.js配置

module.exports = {
	...
		  css: {
		    loaderOptions: {
		      postcss: {
		        plugins: [
		          require("postcss-pxtorem")({
		            // 把px单位换算成rem单位
		            rootValue: 37.5, //换算基数,
		            unitPrecision: 3, //允许REM单位增长到的十进制数字,小数点后保留的位数。
		            propList: ["*"],
		            exclude: /(node_module)/, //默认false,可以(reg)利用正则表达式排除某些文件夹的方法,例如/(node_module)/ 。如果想把前端UI框架内的px也转换成rem,请把此属性设为默认值
		            selectorBlackList: [".van"], //要忽略并保留为px的选择器,本项目我是用的vant ui框架,所以忽略他
		            mediaQuery: false, //(布尔值)允许在媒体查询中转换px。
		            minPixelValue: 1, //设置要替换的最小像素值
		          }),
		        ],
		      },
		    },
		  },
	...
}

3. 动态设置html的font-size大小

/src/utils/resize.js

// 基准大小
const baseSize = 37.5;
// 设置 rem 函数
function setRem() {
  // 当前页面宽度相对于 750 宽的缩放比例
  const clientWidth = document.documentElement.clientWidth;
  // 仅当视口宽度小于800时,视为移动端
  if (clientWidth < 800) {
    const scale = clientWidth / 750;
    // 设置页面根节点字体大小
    document.documentElement.style.fontSize =
      baseSize * Math.min(scale, 2) + "px";
  } else {
    document.documentElement.style.fontSize = "37.5px";
  }
}
// 初始化
setRem();
// 改变窗口大小时重新设置 rem
window.onresize = function() {
  setRem();
};

main.js 引入

import "./utils/resize";

4. 效果如图:

pc端的font-size
vuejs - - - - - 移动端设备兼容(pxtorem)_第1张图片

移动端的font-sizevuejs - - - - - 移动端设备兼容(pxtorem)_第2张图片

你可能感兴趣的:(移动端,html,vue.js)