Malfy,
3 . , , . , .
1) (fastest)
, div, white-space: nowrap, .
$('div.someClass').css('whiteSpace','nowrap');
2) (slowest)
div, - , , css . :
var yourString = 'your string';
var $tempDiv = jQuery('<div style="visibility:hidden;position:absolute;white-space:nowrap">'+jQuery.trim(yourString)+'</div>').appendTo('body');
$newDiv = <your new div, however you're creating it>;
// set the width of the new div to the width of the temp div
$newDiv.width($tempDiv.width());
// and clean up;
$tempDiv.remove();
//repeat as necessary
3) (quite fast too)
Alternatively, if you are sure that you will use a monospace font (courier, console, etc.). There is a much faster way. Keep the width of one character and multiply it by the length of each new text line. This way you are not writing a new item every time. For instance:
var $tempDiv = $('<div style="visibility:hidden;margin:0;padding:0;border:0;">z</div>').appendTo('body');
var reusableCharacterWidth=$tempDiv.width();
$tempDiv.remove();
var firstString = your string';
// set the width of your first div
$newDiv.width(reusableCharacterWidth*firstString.length);
var nextString = 'your next string';
// set the width of your next div
$nextNewDiv.width(reusableCharacterWidth*nextString.length);
(note: you can use $ .trim () for strings just in case)
To get the longest string:
var longestLineLength,
yourText= 'your text here';
function getLongestLineLength(lines){
var oneLineLength,
longest=0,
linesArray = lines.split('\n');
for(var i=0,len=linesArray.length;i<len;i++){
oneLineLength=linesArray[i].length;
longest=oneLineLength>longest?oneLineLength:longest;
}
return longest;
}
longestLineLength = getLongestLineLength(yourText);
Hooray!
Adam
source
share