对于一些萌新来说,怎么设置 rem 与 px 之间的关系,以及 rem 是怎么适应的等等问题都不是很清楚。似是而非的,说熟悉不熟悉,说陌生又不陌生。
我简单的解释一下关于 js 文件中对于 rem 的设定。
请看代码:
;(function (docm, win) {
let docmEL = docm.documentElement
let resize = 'orientationChange' in window ? 'orientationChange' : 'resize'
docmEL.style.fontSize = (16 * docmEL.clientWidth) / 750 + 'px'
let resizeRem = function () {
docmEL.style.fontSize = (16 * docmEL.clientWidth) / 750 + 'px'
}
win.addEventListener(resize, resizeRem, false)
})(document, window)
这是关于rem设置的代码,这里面的很多数据或者属性,萌新都是可以不用怎么在意的或者又说这些东西都是不难的,基本一看就知道各自是什么意思。
现在主要记录两个概念:
1,设计稿图纸大小
就是说你在开发前拿到的图纸是多少的?750px还是640px的,等等。而在这段
(16 * docmEL.clientWidth) / 750
代码中,750字样就是指设计稿大小。
2, rem 与 px 转换关系
就是指实际开发中的 1px 应该对应此时的多少 rem 才是准确的。同样在
(16 * docmEL.clientWidth) / 750
这里,它里面的16就是告诉你,16px = 1rem
另一种 rem 做法
win.addEventListener(resize, resizeRem, false)
})(document, window)
;(function (win, doc) {
function setFontSize() {
var baseFontSize = 100
var baseWidth = 320
var clientWidth = document.documentElement.clientWidth || window.innerWidth
var innerWidth = Math.max(Math.min(clientWidth, 480), 320)
var rem = 100
if (innerWidth > 362 && innerWidth <= 375) {
rem = Math.floor((innerWidth / baseWidth) * baseFontSize * 0.9)
}
if (innerWidth > 375) {
rem = Math.floor((innerWidth / baseWidth) * baseFontSize * 0.84)
}
window.__baseREM = rem
document.querySelector('html').style.fontSize = rem + 'px'
}
var evt = 'onorientationchange' in win ? 'orientationchange' : 'resize'
var timer = null
win.addEventListener(
evt,
function () {
clearTimeout(timer)
timer = setTimeout(setFontSize, 10)
},
false
)
win.addEventListener(
'pageshow',
function (e) {
if (e.persisted) {
clearTimeout(timer)
timer = setTimeout(setFontSize, 10)
}
},
false
)
setFontSize()
})(window, document)