前言
有的时候,我们在使用font-size和rem来给移动端做适配会遇到这样一个问题,在微信中设置字体的大小会影响到rem 的比例,年轻人把字体调小,老年人把字体调大,这样会让我们原本的适配失效,造成页面字体样式错位的问题,下面的代码便可以解决这样的问题。
思路
先动态获取到微信调整字体的比例的倒数 scale,然后对rem 的比例进行还原;
- 先创建一个width为1rem的盒子,并设置为不可见,然后通过获取他的offsetWidth得到它以px为单位的物理宽度instanceWidth(offsetWidth的单位是px),目的是为了计算当前的1rem等于多少px;
- 再获取当前根元素html的font-size值 ,即htmlFontSize(也是以px为单位的),正常情况下1rem = 16px,也就是htmlFontSize等于1rem,但是当被缩放或者放大后就不相等了,我们需要对htmlFontSize与instanceWidth相除 (scale = htmlFontSize / instanceWidth),获取到微信调整字体的比例的倒数scale;
- 为了使 rem 的比例还原,我们要将页面字体的font-size换算后的px的值与scale相乘,将字体大小还原回去。
代码
(function (win, doc) {
//创建一个1rem的盒子
function createScaleElement() {
let scaleDom = document.createElement('div')
scaleDom.style.cssText = 'width:1rem;height:0;overflow:hidden;position:absolute;z-index:-2;visibility:hidden;'
document.body.appendChild(scaleDom)
return scaleDom
}
if (!win.addEventListener) {
return
}
let scaleDom = createScaleElement()
function setFont() {
let scale = toScale()
let html = document.documentElement
let k = 640
html.style.fontSize = (html.clientWidth / k * 100)*scale + 'px'
}
function getOriginalHtmlFontSize() {
let rootDom = document.querySelector('html')
let fontSize = rootDom.style.fontSize || 16
return fontSize
}
function toNum(fontSize) {
if(typeof fontSize === 'string') {
fontSize = fontSize.replace('px', '')
return Number(fontSize)
}
return fontSize
}
function toScale() {
let htmlFontSize = getOriginalHtmlFontSize()
let instanceWidth = scaleDom.offsetWidth
let scale = 1
if(window.getComputedStyle) {
instanceWidth = window.getComputedStyle(scaleDom).width
}
htmlFontSize = toNum(htmlFontSize)
instanceWidth = toNum(instanceWidth)
if(
(typeof htmlFontSize == 'number' && htmlFontSize != 0) &&
(typeof instanceWidth == 'number' && instanceWidth != 0)
) {
if(Math.abs(htmlFontSize-instanceWidth)<0.1) {
return 1
}
scale = htmlFontSize/instanceWidth
}
return scale
}
setFont()
setTimeout(function () {
setFont()
}, 300)
doc.addEventListener('DOMContentLoaded', setFont, false)
win.addEventListener('resize', setFont, false)
win.addEventListener('load', setFont, false)
})(window, document)