html, body {font-size: 16px;}
500 / 16 = 31.25rem
// rem.js 设置 rem 函数
let width = document.documentElement.getBoundingClientRect().width; // 获取宽度
function setRem () {
let orientation = window.matchMedia("(orientation: portrait)");
function onMatchMeidaChange (orientation) {
if (orientation.matches) {
// 竖屏
width = document.documentElement.getBoundingClientRect().width; // 获取竖屏宽度
setTimeout(() => {
// 重新计算竖屏宽度rem
autoRootFontSize()
});
} else {
// 横屏
width = document.documentElement.getBoundingClientRect().width; // 获取横屏宽度
setTimeout(() => {
// 重新计算横屏宽度rem
autoRootFontSize()
});
}
}
onMatchMeidaChange(orientation);
orientation.addListener(onMatchMeidaChange);
/* 计算rem */
function autoRootFontSize () {
// (当前屏幕宽度 || 默认最小宽度为1200) / 1920 * 16px ==> pc 1920 设计稿
let setSize = Math.max(document.documentElement.getBoundingClientRect().width, 1200) / 1920 * 16;
// (当前屏幕宽度 || 默认最小宽度为750) / 750 * 16px ==> 移动端 750 设计稿(适配 pc 默认居中750)
// let setSize = Math.max(document.documentElement.getBoundingClientRect().width, 750) / 750 * 16;
// 字体默认最大值为16px
document.documentElement.style.fontSize = (setSize > 16 ? 16 : setSize) + 'px';
}
window.addEventListener('resize', autoRootFontSize);
autoRootFontSize();
};
window.onresize = function () {
setRem();
}
// main.js 引入
import './common/scripts/rem';
// 配置文件 .postcssrx.config.js
module.exports = {
"plugins": {
"postcss-import": {},
"postcss-url": {},
// to edit target browsers: use "browserslist" field in package.json
"autoprefixer": {
browsers: ['Android >= 4.0', 'iOS >= 7']
},
"postcss-pxtorem": {
viewportWidth: 1920, // (Number) The width of the viewport.
viewportHeight: 1024, // (Number) The height of the viewport.
unitPrecision: 3, // (Number) The decimal numbers to allow the REM units to grow to.
viewportUnit: 'rem', // (String) Expected units.
selectorBlackList: [], // (Array) The selectors to ignore and leave as px.
minPixelValue: 1, // (Number) Set the minimum pixel value to replace.
mediaQuery: false, // (Boolean) Allow px to be converted in media queries.
propList: ['*']
}
}
}
4、开发正常编写对应 px,实际浏览器就会转译为 rem
5、