I think this will do the trick (IE only, of course...):
/Robert
<html>
<head>
<title>Character Width</title>
<style type="text/css">
body, input{font-family:Times;}
</style>
<script language="JavaScript" type="text/javascript">
window.onload = function (){
var oRng = document.body.createTextRange();
var strOrgText = oRng.text;
var oRng;
for(var i=0; i<strOrgText.length; i++){
document.getElementById("parseTextInput").value
strOrgText.substr(i, 1);
alert(strOrgText.substr(i, 1) + ", " +
document.getElementById("parseTextInput").createTextRange().boundingWidth);
}
}
</script>
</head>
<body>
A small monkey...
<input id="parseTextInput" type="text">
</body>
</html>
-----Original Message-----
From: Alex Shiell, ITS, EC, SE [mailto:alex.shiell@s...]
Sent: den 17 september 2001 11:44
To: javascript
Subject: [javascript] RE: character width
No intrinsic way of doing this... you would have to write out the alphabet
in the font you are planning to use, take a screen dump, open it in an
graphics program, zoom in and count the number of pixels that make up each
character. Then, once you have that info, put it all into an array that
matches the character code with its width.
e.g.
(the letters A-Z and a-z have character codes between 65 and 122)
var aCharWidths = new Array()
aCharWidths[65]=8;
aCharWidths[66]=6;
...
aCharWidths[122]=4;
then to find out the width of any character
aCharWidths[s.charCodeAt(n)]
(where s is your string and n is the character position within it)
However this is an awful lot of work to go through for what is essentially a
visual formatting excercise. bear in mind that at some point somebody may
decide they want the whole website to use a different font and then you will
have to go though all this again. You'd be better off playing around with
CSS to get the desired effect that you are trying to acheive.
-----Original Message-----
From: Dimitriy Dribinskiy [mailto:DimitriyD@M...]
Sent: 14 September 2001 22:26
To: javascript
Subject: [javascript] character width
Hello
Is it possible to figure out the width of string in pixels based on
characters which were used.
(for instance ' l ' and ' w ' or '1' and '8' have different wide, but I need
to get exact length)
Thanks
Dmitriy