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.js 1.2 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // rem-resize.js
  2. (function (doc, win) {
  3. 'use strict';
  4. // 配置项
  5. const config = {
  6. designWidth: 1920, // 设计稿宽度
  7. baseFontSize: 16, // 基础字体大小(设计稿下1rem = 16px)
  8. minFontSize: 12, // 最小字体限制
  9. maxFontSize: 24, // 最大字体限制
  10. delay: 300, // 窗口变化时的延迟执行(ms)
  11. };
  12. const docEl = doc.documentElement;
  13. const resizeEvt = 'orientationchange' in win ? 'orientationchange' : 'resize';
  14. let resizeTimeout;
  15. function calculateFontSize() {
  16. const clientWidth = docEl.clientWidth || win.innerWidth;
  17. if (!clientWidth) return;
  18. const fontSize = Math.min(
  19. Math.max((clientWidth / config.designWidth) * config.baseFontSize, config.minFontSize),
  20. config.maxFontSize,
  21. );
  22. docEl.style.fontSize = fontSize + 'px';
  23. // 可选:调试输出
  24. if (win.console) {
  25. console.debug('[REM-Resize]', 'width:', clientWidth, 'font-size:', fontSize + 'px');
  26. }
  27. }
  28. function resizeHandler() {
  29. clearTimeout(resizeTimeout);
  30. resizeTimeout = setTimeout(calculateFontSize, config.delay);
  31. }
  32. calculateFontSize();
  33. // 初始化监听
  34. win.addEventListener(resizeEvt, resizeHandler, false);
  35. })(document, window);