<style>
.canvasText{
font-size: 14px;
max-width: 200px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
<div class="canvasText" :title="isTitle?canvasText:''">
{{ canvasText }}
</div>
1.使用canvas.measureText,获取渲染之前字符串的宽度
const text = 'hello world hello world hello worl'
this.canvasText = text;
const font = "14px arial"
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
context.font = font;
const { width } = context.measureText(text);
console.log('宽度',width);
if(width>200){
this.isTitle = true;
}
2.判断dom节点scrollWidth>offsetWidth,大于则出现了省略号
if(e.target.scrollWidth>e.target.offsetWidth){//是否超出显示省略号
this.isTitle = true;
}