I was looking around the web for a solution and found the following article. The article had an example with an existing TD, however, what you're doing, and what I did, may not be in a TD. So I came up with the following to make it dynamic:
function GetStringPixelWidth(str)
{
var elem = document.createElement('SPAN');
elem.innerHTML = str;
elem.style.visibility = 'hidden';
document.body.appendChild(elem);
var w = elem.offsetWidth;
document.body.removeChild(elem);
return w;
}
{
var elem = document.createElement('SPAN');
elem.innerHTML = str;
elem.style.visibility = 'hidden';
document.body.appendChild(elem);
var w = elem.offsetWidth;
document.body.removeChild(elem);
return w;
}
One must append it to the document so the offsetWidth is actually calculated. I added it to the body, but you can add it to the parentElement that str is coming from so you can get the width of wrapping text.
UPDATE: I found that in Mozilla FireFox, adding the TD doesn't work. In light of this, I've updated the code to instead add a SPAN element. I'm thinking FF doesn't know how to handle adding a single TD into the document; it kept returning 2 as the offsetWidth. It didn't matter if I created TABLE and TR elements and nested them. Always 2. With the span, it's still a dynamic width, unlike DIVs, and can be independently added to the page with no issues.
No comments:
Post a Comment