// 默认rem换算px 1rem = 16px
const defSize = 16;
// 默认px换算rem比率
const defPxRatio = 1 / defSize;
// 默认px换算rem 100倍比率
const tallNum = defPxRatio * 100;
// 默认浏览宽度 1920 宽度下html font-size为6.25% 用于计算1920上下范围自适应
// 可以自行调整宽度,需要注意的是一些浏览器在太小的浏览器宽度下不进行计算了(欢迎解释)
// 比如谷歌设置1280下明显html font-size不管用
const defWidth = 1920;
// 默认宽度百分比
const defRatio = 100 / (defWidth / defSize);
// 当前使用浏览器
const browser = navigator.userAgent.toLowerCase();
const adaptive = (doc, win)=> {
const docEl = doc.documentElement,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
recalc = () => {
const clientWidth = docEl.clientWidth;
if (!clientWidth) return;
// 即时获取宽度百分比
const ratio = clientWidth / defSize;
// 即时换算比率 即时宽度百分比 * 默认宽度百分比 * px换算rem比率
const fontSize = ratio * defRatio * defPxRatio;
// 如果是谷歌内核并且fontSize高于px换算rem比率则固定为该比率
if(browser.indexOf('chrome') > -1 && fontSize < tallNum){
docEl.style.fontSize = `${tallNum}%`
}else{
// 更改html fontSize
docEl.style.fontSize = `${fontSize}%`;
}
};
if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener('DOMContentLoaded', recalc, false);
}
// 初始化
adaptive(document, window);
//随浏览器大小自适应
window.onresize = function() {
adaptive(document, window);
}
以rem为单位或百分比。
经过换算现在1rem = 1px 所以放心的用ui给的px像素单位值都是 1:1 的