|
- (function (doc, win) {
- 'use strict';
-
- // 配置项
- const config = {
- // 断点设置(单位:px)
- // 1440 1560 1680 1800 1920 2040 2160 2280 2400 2520
- breakpoints: [
- { minWidth: 2520, fontSize: 22 }, // 21
- { minWidth: 2280, fontSize: 20 }, // 19
- { minWidth: 2040, fontSize: 18 }, // 17
- { minWidth: 1800, fontSize: 16 }, // 15
- { minWidth: 1560, fontSize: 14 }, // 13
- { minWidth: 0, fontSize: 12 },
- ],
- delay: 300 // 防抖延迟(ms)
- };
-
- const docEl = doc.documentElement;
- const resizeEvt = 'orientationchange' in win ? 'orientationchange' : 'resize';
- let resizeTimeout;
-
- // 计算当前宽度对应的字体大小
- function calculateFontSize() {
- const clientWidth = docEl.clientWidth || win.innerWidth;
- if (!clientWidth) return;
-
- // 从大到小匹配断点
- const targetBreakpoint = config.breakpoints.find(
- bp => clientWidth >= bp.minWidth
- );
-
- // 设置字体大小
- docEl.style.fontSize = targetBreakpoint.fontSize + 'px';
-
- // 调试输出(可选)
- console.debug('[REM-Resize]',
- 'Width:', clientWidth + 'px',
- 'Font-Size:', targetBreakpoint.fontSize + 'px');
- }
-
- // 防抖处理
- function handleResize() {
- clearTimeout(resizeTimeout);
- resizeTimeout = setTimeout(calculateFontSize, config.delay);
- }
-
- calculateFontSize();
-
- // 初始化监听
- win.addEventListener(resizeEvt, handleResize, false);
- })(document, window);
|