After opening the browser, px is automatically converted to rem (vue) postcss-pxtorem

Px is automatically converted to rem (vue) postcss-pxtorem after opening the browser

  1. yarn add postcss-pxtorem 安装
    Open the package.json file to see if the installation is successful "postcss-pxtorem": "^5.1.1",

  2. 新建rem.js文件

	(function (win) {
    
    
	    var docEl = win.document.documentElement;
	    var time;
	    function refreshRem() {
    
    
	      var width = docEl.getBoundingClientRect().width;
	      if (width > 768) {
    
     // 最大宽度
	        width = 768;
	      }
	      var rem = width / 375 * 100;
	      docEl.style.fontSize = rem + 'px';
	      ///rem用font-size:50px来进行换算
	    }
	    win.addEventListener('resize', function () {
    
    
	      clearTimeout(time);
	      time = setTimeout(refreshRem, 1);
	    }, false);
	    win.addEventListener('pageshow', function (e) {
    
    
	      if (e.persisted) {
    
    
	        clearTimeout(time);
	        time = setTimeout(refreshRem, 1);
	      }
	    }, false);
	    refreshRem();
	  })(window);
  1. 新建vue.config.js文件
	module.exports = {
    
    
	  css: {
    
    
	    loaderOptions: {
    
    
	      postcss: {
    
    
	        plugins: [
	          require('postcss-pxtorem')({
    
     // 把px单位换算成rem单位
	            rootValue: 100 ,// 换算的基数(设计图750的根字体为32)
	            propList: ['*']
	          })
	        ]
	      }
	    }
	  },
	}
	rootValue (Number | Function):设置根元素字体大小或根据输入参数返回根元素字体大小
	unitPrecision (Number):允许REM单位增长的十进制数字
	propList (Array) :属性的选择器,*表示通用
	selectorBlackList (Array):忽略转换正则匹配项。如果个别地方不想转化px。可以简单的使用大写的 PX 或 Px
	replace (Boolean) :替换包含rems的规则
	mediaQuery (Boolean):允许在媒体查询中转换px
	minPixelValue (Number) :设置要替换的最小像素值
	exclude (String, Regexp, Function) :要忽略并保留为px的文件路径
  1. 打开main.js
	import './rem' //引入 注意链接
	import '../vue.config' //引入 注意链接

After the operation is complete, open the browser and you will find that the px you wrote has been converted to rem, but the file you wrote still belongs to the px unit

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_54645059/article/details/112730435