马尔菲,
想到了 3 种获取字符串宽度的方法。我会先介绍这些,然后是如何获得最长的长度。看起来其他人已经解决了这个正则表达式。
1) (fastest)
如果只有文本本身需要一定宽度,而不是 div,那么您可以使用 white-space:nowrap 来确保文本保持全宽。
$('div.someClass').css('whiteSpace','nowrap');
2) (slowest)
如果您需要一个字符串的像素宽度来设置另一个 div 的宽度,一种方法是创建一个包含该字符串的元素并使用上面的 css 属性。示例:
var yourString = 'your string';
// create a div containing 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)
或者,如果您确定要使用等宽字体(courier、consolas 等)。有一个更快的方法。保存单个字符的宽度并将其乘以每个新文本字符串的长度。这样你就不会每次都写一个新元素。例如:
var $tempDiv = $('<div style="visibility:hidden;margin:0;padding:0;border:0;">z</div>').appendTo('body');
//(any character will work. z is just for example);
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);
(注意:您可能需要在字符串上使用 $.trim() 以防万一)
获取最长的字符串:
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);
干杯!
亚当