当前位置: 首页 > Web前端 > JavaScript

计算字符串占用宽度像素的方法

时间:2023-03-27 00:18:07 JavaScript

//计算字符串占用宽度的方法constgetTextWidth=(text:string,fontSize:number,fontWeight:string)=>{//创建临时元素constele:HTMLElement=document.createElement('div');ele.style.position='绝对';ele.style.whiteSpace='nowrap';ele.style.fontSize=fontSize+'px';ele.style.fontWeight=fontWeight;ele.innerText=文本;document.body.append(ele);//获取span的宽度constwidth:number=ele.getBoundingClientRect().width;//从body中移除spandocument.body.removeChild(ele);console.log(text+'_'+width);//返回跨度宽度returnwidth;};