实践思路:用rem布局,再结合JS动态控制document.documentElement.style.fontSize大小。
注意事项:win和mac系统的设备像素比(devicePixelRatio)不同,win系统默认devicePixelRatio=1(可以通过桌面右键->显示设置),而mac系统默认devicePixelRatio=2
代码输出:
((win) => { var doc = win.document var docEl = doc.documentElement var initFontSize = 16 var tid function refreshRem() { var agent = navigator.userAgent.toLowerCase() var isMac = /macintosh|mac os x/i.test(navigator.userAgent) var rem = initFontSize if (~agent.indexOf('win32') || ~agent.indexOf('wow32') || ~agent.indexOf('win64') || ~agent.indexOf('wow64')) { rem = initFontSize / win.devicePixelRatio } if (isMac) { rem = initFontSize / (win.devicePixelRatio / 2) } docEl.style.fontSize = rem + 'px' } win.addEventListener('resize', () => { clearTimeout(tid) tid = setTimeout(refreshRem, 300) }, false) win.addEventListener('pageshow', (e) => { if (e.persisted) { clearTimeout(tid) tid = setTimeout(refreshRem, 300) } }, false) if (doc.readyState === 'complete') { refreshRem() } else { doc.addEventListener('DOMContentLoaded', (e) => { refreshRem() }, false) } refreshRem() })(window)
实际引用:
1、单页面应用场景下,直接在main.js里面引入即可
2、多页面应用场景下,直接每个页面引入即可