采用rem为单位,根据屏幕的宽度调整html的font-size。
获取屏幕宽度并计算比例:
function fontSize(res){
const clientWidth = window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth;
if (!clientWidth) return;
let fontSize = clientWidth / 1920;
return res*fontSize;
}
在需要设置字体的地方可以这样写,
如在1920屏宽下字体设置为12px,就可以传入12给fontSize
tooltip : {
trigger: 'axis',
textStyle:{
fontSize: fontSize(12),
}
},
当浏览器窗口发生改变的时候,需要重绘图表,才能实现实时改变echarts字体
window.addEventListener('resize',()=>{
this.refreshChart();
})
// vue
setFontOption() {
this.chart.setOption({
tooltip : {
textStyle:{
fontSize: fontSize(12),
}
}
})
},
refreshChart() {
if (!this.chart) return;
this.chart.resize();
this.setFontOption();
}
本文介绍了一种使用rem单位和屏幕宽度动态调整字体大小的方法。通过计算屏幕宽度与基准宽度的比例,实现不同屏幕尺寸下的字体自适应。适用于echarts等图表组件,确保在窗口大小变化时字体实时更新。


被折叠的 条评论
为什么被折叠?



