Javscript常用封装(二)


1.计算字符串的占位宽度

提示:字符串的占位宽度除了涉及到具体的字符串内容,还与字体大小有关

//计算字符串的占位宽度
function getTextWidth(str = '',font_size=12) {
    const dom = document.createElement('span')
    dom.style.display = 'inline-block'
    dom.style['font-size'] = font_size + 'px'
    dom.textContent = str
    document.body.appendChild(dom)
    const width = dom.clientWidth
    document.body.removeChild(dom)
    return width;
}

//计算字符串数组中的最大宽度
function getMaxWidthByArray(text_arr=[],font_size=12){
    //计算设备编号占位的最大宽度
    var max_width = 0
    text_arr.forEach(function(str){
        var now_text_width = getTextWidth(str,font_size)
        if(now_text_width > max_width){
            max_width = now_text_width
        }
    })
    return max_width
}