js中,怎么计算一个字符串宽度?

阅读更多

http://bbs.csdn.net/topics/300032210

function textSize(fontSize, text) {
    var span = document.createElement("span");
    var result = {};
    result.width = span.offsetWidth;
    result.height = span.offsetWidth;
    span.style.visibility = "hidden";
    document.body.appendChild(span);
    if (typeof span.textContent != "undefined")
        span.textContent = text;
    else span.innerText = text;
    result.width = span.offsetWidth - result.width;
    result.height = span.offsetHeight - result.height;
    span.parentNode.removeChild(span);
    return result;
}

var size = textSize("9px", "囧");
alert("宽:" + size.width + " 高:" + size.height);

 

 

http://bbs.csdn.net/topics/390496387

 

 



你可能感兴趣的:(js中,怎么计算一个字符串宽度?)