89 lines
2.5 KiB
JavaScript
89 lines
2.5 KiB
JavaScript
|
(function flexible(window, document) {
|
|||
|
const docEl = document.documentElement;
|
|||
|
// const dpr = window.devicePixelRatio || 1;
|
|||
|
const dpr = 1;
|
|||
|
|
|||
|
// adjust body font size
|
|||
|
function setBodyFontSize() {
|
|||
|
if (document.body) {
|
|||
|
document.body.style.fontSize = 12 * dpr + "px";
|
|||
|
} else {
|
|||
|
document.addEventListener("DOMContentLoaded", setBodyFontSize);
|
|||
|
}
|
|||
|
}
|
|||
|
setBodyFontSize();
|
|||
|
|
|||
|
const browser = {
|
|||
|
versions: (function () {
|
|||
|
const u = navigator.userAgent;
|
|||
|
// const app = navigator.appVersion;
|
|||
|
return {
|
|||
|
trident: u.includes("Trident") > -1,
|
|||
|
presto: u.includes("Presto") > -1,
|
|||
|
webkit: u.includes("AppleWebkit") > -1,
|
|||
|
gecko: u.includes("Gecko") > -1,
|
|||
|
mobile: !!u.match(/AppleWebKit.*Mobile.*/),
|
|||
|
ios: !!u.match(/\(i[^;]+;(U;)? CPU.+Mac OS X/),
|
|||
|
android: u.includes("Android") > -1,
|
|||
|
iPhone: u.includes("iPhone") > -1,
|
|||
|
iPad: u.includes("iPad") > -1,
|
|||
|
};
|
|||
|
})(),
|
|||
|
};
|
|||
|
|
|||
|
function refreshRem() {
|
|||
|
let width = docEl.getBoundingClientRect().width;
|
|||
|
if (!browser.versions.mobile) {
|
|||
|
if (width > 1920) {
|
|||
|
width = 1920;
|
|||
|
} else if (width < 1200) {
|
|||
|
width = 1200;
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
if (width / dpr > 540) {
|
|||
|
width = width * dpr;
|
|||
|
}
|
|||
|
let rem;
|
|||
|
// console.log(browser.versions.mobile);
|
|||
|
if (browser.versions.mobile) {
|
|||
|
rem = width / 7.5;
|
|||
|
} else {
|
|||
|
// >1600
|
|||
|
rem = width / 19.2;
|
|||
|
}
|
|||
|
docEl.style.fontSize = rem + "px";
|
|||
|
flexible.rem = window.rem = rem;
|
|||
|
}
|
|||
|
refreshRem();
|
|||
|
// 由于我们设计稿pc宽度为1920,移动端宽度为750,所以在使得100px=1rem的基准下,分别使得当前width/19.2和width/7.5。
|
|||
|
|
|||
|
// // set 1rem = viewWidth / 10
|
|||
|
// function setRemUnit() {
|
|||
|
// const rem = docEl.clientWidth / 10;
|
|||
|
// docEl.style.fontSize = rem + "px";
|
|||
|
// }
|
|||
|
// setRemUnit();
|
|||
|
|
|||
|
// reset rem unit on page resize
|
|||
|
window.addEventListener("resize", refreshRem);
|
|||
|
window.addEventListener("pageshow", function (e) {
|
|||
|
if (e.persisted) {
|
|||
|
refreshRem();
|
|||
|
}
|
|||
|
});
|
|||
|
|
|||
|
// detect 0.5px supports
|
|||
|
if (dpr >= 2) {
|
|||
|
const fakeBody = document.createElement("body");
|
|||
|
const testElement = document.createElement("div");
|
|||
|
testElement.style.border = ".5px solid transparent";
|
|||
|
fakeBody.appendChild(testElement);
|
|||
|
docEl.appendChild(fakeBody);
|
|||
|
if (testElement.offsetHeight === 1) {
|
|||
|
docEl.classList.add("hairlines");
|
|||
|
}
|
|||
|
docEl.removeChild(fakeBody);
|
|||
|
}
|
|||
|
})(window, document);
|