字体自适应大小一行展示,最小为12,若还是超出则css的...代替
代码,以300px宽度为例
<template> <div class="comparyname" ref="comparyName"><div class="comparyname2">公司名称:目的地看似课的手机待机时间程VS的说几句参加考试的</div></div> </template> <script> import { onMounted, ref} from 'vue'; export default { name: "iwebOffice", components:{}, setup() { const comparyName = ref(null) /** * text:文本 * maxWidth:文本最大宽度 * fontFamily:字体 * minSize:最小字号 * maxSize:最大字号 * * 此处设置最小字体为12,若12还超出给定宽度,可以使用css的...来实现一行展示,若不超出,则一点一点加大字体,找到最适合的一个字号,最大为50可更改 */ const getNewFont = function(text,maxWidth,fontFamily,minSize=12,maxSize=50){ //创建画布 let canvas = document.createElement('canvas') let context = canvas.getContext('2d'); //找出能适应的最大字体 for(var i=minSize;i<maxSize;i++){ //给画布设置字体和字体大小,并获取此时宽度,判断是否超出最大宽度,返回合适的值 context.font = i+"px "+fontFamily; const detail = context.measureText(text); const width = detail.width; if(width==maxWidth){ return i } if(width>maxWidth){ return i-1 } } return i>maxSize?maxSize:i; } onMounted(()=>{ let dom = comparyName.value const text = dom.innerText const fontFamily = getComputedStyle(dom).fontFamily let swidth = parseInt(getComputedStyle(dom).width) let newFont = getNewFont(text,swidth,fontFamily,12,30) dom.style.fontSize = newFont+'px' }) return { comparyName }; } } </script> <style scoped> .comparyname{ margin-left: 100px; width: 300px; } .comparyname2{ position: relative; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; color: #444; font-weight: bold; } </style>
效果图
未超出
超出
截图原因,宽度都是300px
标签:12,展示,text,dom,一行,fontFamily,let,字体 From: https://www.cnblogs.com/lijun12138/p/17385938.html