2
0

flexible.ts 985 B

1234567891011121314151617181920212223242526272829303132333435
  1. export function flexible(options: { minWidth?: number }) {
  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. // detect 0.5px supports
  20. if (dpr >= 2) {
  21. const fakeBody = document.createElement("body");
  22. const testElement = document.createElement("div");
  23. testElement.style.border = ".5px solid transparent";
  24. fakeBody.appendChild(testElement);
  25. docEl.appendChild(fakeBody);
  26. if (testElement.offsetHeight === 1) {
  27. docEl.classList.add("hairlines");
  28. }
  29. docEl.removeChild(fakeBody);
  30. }
  31. }