获取一段文字的像素长度

/*
text: 文字串
font: 文字所具有的字体样式信息,可以通过$("xxxx").css("font")获得。注意,$("xxxx").css("font")在火狐下面可能会获取不到信息,可以具体的获取$("xxxx").css("font-size"),$("xxxx").css("font-family")然后再自己拼凑font的css样式信息
*/
function getTextPixelWidth(text, fontStyle){
     var span = document.createElement("span");
     span.style.cssText = "visibility:hidden;display:inline-block;white-space:nowrap;" + fontStyle;
     document.body.appendChild(span);
     text = text.replace(/ /g, " ");
     span.innerHTML = text;
     var pixelCount = span.offsetWidth;
     document.body.removeChild(span);
     return pixelCount;  
}

 

posted @ 2017-09-15 14:29  herohh  阅读(1121)  评论(0编辑  收藏  举报