[JavaScript] 根据字符串宽度截取字符串

时间:2023-03-08 18:15:08
/**
* 根据字符串宽度截取字符串
* @param desc 原始字符串
* @param width 该显示的宽度
* @param fontsize 字体大小 12px
* @returns {string}
*/
function cutStringByWith(desc,width,fontsize) { if($('#word-cut').length==0){
$('body').append('<span id="word-cal" style="visibility: hidden; white-space: nowrap;font-size: '+fontsize+';"></span> ')
}
var temp_desc="";//存放截断字符串
for(var j=0;j<desc.length;j++){
//desc是目标字符串,
temp_desc+=desc[j];
$('#word-cut').text(temp_desc);
if($('#word-cut').width()>width){
break;
}
}
temp_desc+="..";
return temp_desc;
}