flexible.js 994 B

123456789101112131415161718192021222324252627282930
  1. export function flexible(options) {
  2. const docEl = document.documentElement;
  3. const dpr = window.devicePixelRatio || 1;
  4. function setRemUnit() {
  5. let cwidth = docEl.clientWidth;
  6. if (options.minWidth) {
  7. cwidth = Math.max(cwidth, options.minWidth);
  8. }
  9. const rem = cwidth / 10;
  10. docEl.style.fontSize = rem + "px";
  11. }
  12. setRemUnit();
  13. window.addEventListener("resize", setRemUnit);
  14. window.addEventListener("pageshow", function (e) {
  15. if (e.persisted) {
  16. setRemUnit();
  17. }
  18. });
  19. if (dpr >= 2) {
  20. const fakeBody = document.createElement("body");
  21. const testElement = document.createElement("div");
  22. testElement.style.border = ".5px solid transparent";
  23. fakeBody.appendChild(testElement);
  24. docEl.appendChild(fakeBody);
  25. if (testElement.offsetHeight === 1) {
  26. docEl.classList.add("hairlines");
  27. }
  28. docEl.removeChild(fakeBody);
  29. }
  30. }