For some newcomers, how to set the relationship between rem and px, and how rem adapts, etc. are not very clear. Specious, say familiar or unfamiliar, say unfamiliar and not unfamiliar.
Let me briefly explain the setting of rem in the js file.
Please see the code:
;(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)
This is the code for rem settings. There are many data or attributes in it. Mengxin doesn't need to pay much attention or it is not difficult to say that these things are not difficult. You can basically know what each means at a glance.
Two concepts are mainly recorded now:
1. The size of the design draft
In other words, how many drawings did you get before development? 750px or 640px, etc. And in this paragraph
(16 * docmEL.clientWidth) / 750
In the code, the word 750 refers to the size of the design draft.
2. Conversion relationship between rem and px
It means how much rem should correspond to 1px in actual development at this time is accurate. Same in
(16 * docmEL.clientWidth) / 750
Here, the 16 in it tells you,16px = 1rem
Another rem approach
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)