javascript获取html/svg页面一个字符串(文本)的宽度

javascript获取html/svg页面一个字符串(文本)的宽度

1.思路

    <1.新建一个span
    <2.将被选文本信息放入span
    <3.获取span信息,进而获取被选文本信息

2.参考程序如下

    <1.程序

function textSize(fontSize,text) {
    //fontSize:代表汉字的大小,英文字会自动按照默认值
    var span = document.createElement("span");
    var result = {};
    result.width = span.offsetWidth;
    result.height = span.offsetWidth;
    span.style.visibility = "hidden";
    span.style.fontSize = fontSize;
    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;
}

    <2.返回值

{width:"xxx",height:"xxx"}

经验分享 程序员 微信小程序 职场和发展