Files
aida_front/src/tool/flexible.js
X1627315083 4a65772ca9 fix
2024-12-18 17:38:43 +08:00

49 lines
1.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
let flexible = (designWidth, maxWidth,minWidth) =>{
var doc = document, win = window, docEl = doc.documentElement, remStyle = document.createElement("style"), tid;
designWidth = designWidth || 1920;
maxWidth = maxWidth || 2560;
minWidth = minWidth || 1024;
function refreshRem() {
var width = docEl.getBoundingClientRect().width;
var height = docEl.getBoundingClientRect().height;
maxWidth = maxWidth || 1920;
if(width/height>1.98) width = height * 1.98;
width > maxWidth && (width = maxWidth);
width < minWidth && (width = minWidth);
var rem = width * 10 / designWidth;
// var rem = Math.round(width * 10 / designWidth);
docEl.style.fontSize = rem+'px'
remStyle.innerHTML = 'html{font-size:' + rem + 'px;}';
}
// if (docEl.firstElementChild) {
// docEl.firstElementChild.appendChild(remStyle);
// } else {
// var wrap = doc.createElement("div");
// wrap.appendChild(remStyle);
// doc.write(wrap.innerHTML);
// wrap = null;
// }
//要等 wiewport 设置好后才能执行 refreshRem不然 refreshRem 会执行2次
refreshRem();
win.addEventListener("resize", function() {
clearTimeout(tid); //防止执行两次
tid = setTimeout(refreshRem, 300);
}, false);
win.addEventListener("pageshow", function(e) {
if (e.persisted) { // 浏览器后退的时候重新计算
clearTimeout(tid);
tid = setTimeout(refreshRem, 300);
}
}, false);
if (doc.readyState === "complete") {
doc.body.style.fontSize = "16px";
} else {
doc.addEventListener("DOMContentLoaded", function(e) {
doc.body.style.fontSize = "16px";
}, false);
}
};
export default flexible