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

/**
 * 根据字符串宽度截取字符串
 * @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;
}

 

posted on 2017-11-19 20:23  晏过留痕  阅读(2482)  评论(0编辑  收藏  举报