38 lines
1.3 KiB
JavaScript
38 lines
1.3 KiB
JavaScript
|
|
import { getUniversalZoomLevel } from '@/utils/tools'
|
|||
|
|
|
|||
|
|
const maxWidth = 1920;
|
|||
|
|
const minWidth = 500;
|
|||
|
|
const maxHeight = 1080;
|
|||
|
|
const minHeight = 500;
|
|||
|
|
let flexible = (designWidth = 1920, designHeight = 1080) => {
|
|||
|
|
var doc = document, win = window, docEl = doc.documentElement, remStyle = document.createElement("style"), tid;
|
|||
|
|
function refreshRem() {
|
|||
|
|
var width = docEl.getBoundingClientRect().width;
|
|||
|
|
var height = docEl.getBoundingClientRect().height;
|
|||
|
|
width = getUniversalZoomLevel() * width
|
|||
|
|
height = getUniversalZoomLevel() * height
|
|||
|
|
if (width > maxWidth) width = maxWidth;
|
|||
|
|
if (width < minWidth) width = minWidth;
|
|||
|
|
if (height > maxHeight) height = maxHeight;
|
|||
|
|
if (height < minHeight) height = minHeight;
|
|||
|
|
const wrem = (width * 10 / designWidth).toFixed(2);
|
|||
|
|
const hrem = (height * 10 / designHeight).toFixed(2);
|
|||
|
|
const rem = Math.min(wrem, hrem);
|
|||
|
|
docEl.style.fontSize = rem + 'px'
|
|||
|
|
}
|
|||
|
|
//要等 wiewport 设置好后才能执行 refreshRem,不然 refreshRem 会执行2次;
|
|||
|
|
refreshRem();
|
|||
|
|
win.addEventListener("resize", function () {
|
|||
|
|
clearTimeout(tid); //防止执行两次
|
|||
|
|
tid = setTimeout(refreshRem, 200);
|
|||
|
|
}, false);
|
|||
|
|
|
|||
|
|
win.addEventListener("pageshow", function (e) {
|
|||
|
|
if (e.persisted) { // 浏览器后退的时候重新计算
|
|||
|
|
clearTimeout(tid);
|
|||
|
|
tid = setTimeout(refreshRem, 200);
|
|||
|
|
}
|
|||
|
|
}, false);
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
export default flexible
|