You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

resize-breakpoint.js 1.5 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. (function (doc, win) {
  2. 'use strict';
  3. // 配置项
  4. const config = {
  5. // 断点设置(单位:px)
  6. // 1440 1560 1680 1800 1920 2040 2160 2280 2400 2520
  7. breakpoints: [
  8. { minWidth: 2520, fontSize: 22 }, // 21
  9. { minWidth: 2280, fontSize: 20 }, // 19
  10. { minWidth: 2040, fontSize: 18 }, // 17
  11. { minWidth: 1800, fontSize: 16 }, // 15
  12. { minWidth: 1560, fontSize: 14 }, // 13
  13. { minWidth: 0, fontSize: 12 },
  14. ],
  15. delay: 300 // 防抖延迟(ms)
  16. };
  17. const docEl = doc.documentElement;
  18. const resizeEvt = 'orientationchange' in win ? 'orientationchange' : 'resize';
  19. let resizeTimeout;
  20. // 计算当前宽度对应的字体大小
  21. function calculateFontSize() {
  22. const clientWidth = docEl.clientWidth || win.innerWidth;
  23. if (!clientWidth) return;
  24. // 从大到小匹配断点
  25. const targetBreakpoint = config.breakpoints.find(
  26. bp => clientWidth >= bp.minWidth
  27. );
  28. // 设置字体大小
  29. docEl.style.fontSize = targetBreakpoint.fontSize + 'px';
  30. // 调试输出(可选)
  31. console.debug('[REM-Resize]',
  32. 'Width:', clientWidth + 'px',
  33. 'Font-Size:', targetBreakpoint.fontSize + 'px');
  34. }
  35. // 防抖处理
  36. function handleResize() {
  37. clearTimeout(resizeTimeout);
  38. resizeTimeout = setTimeout(calculateFontSize, config.delay);
  39. }
  40. calculateFontSize();
  41. // 初始化监听
  42. win.addEventListener(resizeEvt, handleResize, false);
  43. })(document, window);