为了能够达到根据不同设备之间自适应,我们先要识别用户设备的分辨率然后再给html设置大小,然后在写css过程中只要使用rem就可以能够做到自适应。
下面贴上代码:
fontSize() {
let size;
let winW = document.documentElement.clientWidth;
if (winW > 375) {
size = Math.round(winW / 3.9);
} else if (winW >= 320 && winW < 375) {
size = Math.round(winW / 3.6);
if (size < 90) {
size = 90;
}
} else {
size = 100;
}
if (size > 100 && winW < 450) {
size = 100;
} else if (size > 150) {
size = 150;
}
document.documentElement.style.fontSize = size + 'px';
},
上面代码在后续用户使用过程中有用户反馈,调整手机设置页面大小后字体太大导致页面变形。
在查找资料后找到一篇大佬写的文章,通过获取用户缩放大小结合上面代码解决这个问题,这里附上大佬的原文链接:https://blog.csdn.net/qq_45915537/article/details/107378917
createScaleElement() { // 创建1rem宽度的不可见元素
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
},
getOriginalHtmlFontSize() {
let rootDom = document.querySelector('html')
let fontSize = rootDom.style.fontSize || 16
console.log(fontSize)
return fontSize
},
toNum(fontSize) {
if(typeof fontSize === 'string') {
fontSize = fontSize.replace('px', '')
return Number(fontSize)
}
return fontSize
},
toScale() {
let scaleDom = this.createScaleElement()
let htmlFontSize = this.getOriginalHtmlFontSize()
let instanceWidth = scaleDom.offsetWidth
let scale = 1
if(window.getComputedStyle) {
instanceWidth = window.getComputedStyle(scaleDom).width
}
htmlFontSize = this.toNum(htmlFontSize)
instanceWidth = this.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
},
最终代码:
fontSize() {
let size;
let winW = document.documentElement.clientWidth;
if (winW > 375) {
size = Math.round(winW / 3.9);
} else if (winW >= 320 && winW < 375) {
size = Math.round(winW / 3.6);
if (size < 90) {
size = 90;
}
} else {
size = 100;
}
if (size > 100 && winW < 450) {
size = 100;
} else if (size > 150) {
size = 150;
}
document.documentElement.style.fontSize = size + 'px';
let scale = toScale();
document.documentElement.style.fontSize = (scale * size) + 'px';
},
这样就计算出了用户的缩放比例,我们再用缩放比例scale*fontSize就可以还原字体大小了
浙公网安备 33010602011771号