rem 的使用
1.填加以下代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | ( function (designWidth, maxWidth) { var doc = document, win = window, docEl = doc.documentElement, remStyle = document.createElement( "style" ), tid; function refreshRem() { var width = docEl.getBoundingClientRect().width; maxWidth = maxWidth || 540; width > maxWidth && (width = maxWidth); var rem = width * 100 / designWidth; remStyle.innerHTML = 'html{font-size:' + rem + 'px;}' ; // console.log('html{font-size:' + rem + 'px;}') } if (docEl.firstElementChild) { docEl.firstElementChild.appendChild(remStyle); } else { var wrap = doc.createElement( "div" ); wrap.appendChild(remStyle); doc.write(wrap.innerHTML); wrap = null ; } refreshRem(750); win.addEventListener( "resize" , function () { clearTimeout(tid); tid = setTimeout(refreshRem, 300); }, false ); win.addEventListener( "pageshow" , function (e) { if (e.persisted) { clearTimeout(tid); tid = setTimeout(refreshRem, 300); } }, false ); if (doc.readyState === "complete" ) { doc.body.style.fontSize = "16px" ; } else { doc.addEventListener( "DOMContentLoaded" , function (e) { doc.body.style.fontSize = "16px" ; }, false ); } })(750, 1024); |
补充: em相对于父元素,rem相对于根元素。
简单版
(function () {
var docEl = document.documentElement;
var resize = 'orientationchange' in window ? 'orientationchange' : 'resize';
var setRem = function () {
var screenWidth = docEl.clientWidth || window.screen.width || 375;
// 1080 PSD宽度(可变的)
docEl.style.fontSize = (100 * screenWidth / 375) + 'px';
};
window.addEventListener('resize', setRem, false);
setRem();
})(); // 用法psd量出来的像素距离 除以100 比如psd: 100px 转换后 1rem;
https://www.tongbiao.xyz/
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步