Entry
How can I measure the dimensions of a string written with a certain style?
Feb 15th, 2009 21:34
Inschi jelii, Martin Honnen,
The following code which works with NN4, NN6, and IE4+ writes a test
layer containing the string and returns its dimensions:
<HTML>
<HEAD>
<STYLE>
.orange {
font-size: 24pt;
color: white;
background-color: orange;
}
.blue {
font-size: 36px;
color: blue;
}
</STYLE>
<SCRIPT>
function getStringDimensions (string, styleClassName) {
var dim = new Object();
if (document.layers) {
var l = new Layer(window.innerWidth);
l.document.open();
if (styleClassName)
l.document.write('<SPAN CLASS="' + styleClassName + '">' + string
+ '<\/SPAN>');
else
l.document.write(string);
l.document.close();
dim.width = l.document.width;
dim.height = l.document.height;
}
else if (document.all && document.body.insertAdjacentHTML) {
var html = '';
html += '<SPAN ID="testSpan"';
html += ' STYLE="position: absolute; visibility: hidden;"';
if (styleClassName)
html += ' CLASS="' + styleClassName + '"';
html += '>';
html += string;
html += '<\/SPAN>';
document.body.insertAdjacentHTML('beforeEnd', html);
dim.width = document.all.testSpan.offsetWidth;
dim.height = document.all.testSpan.offsetHeight;
document.all.testSpan.outerHTML = '';
}
else if (document.getElementById && document.createElement) {
var span = document.createElement('SPAN');
span.id = 'testSpan';
span.style.position = 'absolute';
span.style.visibility = 'hidden';
if (styleClassName)
span.className = styleClassName;
span.appendChild(document.createTextNode(string));
document.body.appendChild(span);
dim.width = span.offsetWidth;
dim.height = span.offsetHeight;
document.body.removeChild(span);
}
return dim;
}
function checkStringDimensions (form) {
var string = form.string.value;
var styleClassName;
if (form.styleClassName.selectedIndex != 0)
styleClassName = form.styleClassName.options
[form.styleClassName.selectedIndex].value;
var dimensions = getStringDimensions (string, styleClassName);
form.width.value = dimensions.width;
form.height.value = dimensions.height;
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="gui">
string:
<INPUT TYPE="text" NAME="string" VALUE="Kibology for all.">
<BR>
style class:
<SELECT NAME="styleClassName">
<OPTION VALUE="none">none
<OPTION VALUE="orange">orange
<OPTION VALUE="blue">blue
</SELECT>
<INPUT TYPE="button" VALUE="check string dimensions"
ONCLICK="checkStringDimensions(this.form);"
>
<BR>
width:
<INPUT TYPE="text" NAME="width" SIZE="4">
height:
<INPUT TYPE="text" NAME="height" SIZE="4">
</FORM>
</BODY>
</HTML>
http://lahjatideoita.blogspot.com
http://ideaspara-regalar.blogspot.com
http://idearegalo1.blogspot.com
http://geschenkeidee.blogspot.com
http://darkovenapady.blogspot.com