这个 JSFiddle展示了一个简单的解决方案:
/**
* Uses canvas.measureText to compute and return the width of the given text of given font.
*
* @param text The text to be rendered.
* @param {String=} fontStyle The style of the font (e.g. "bold 12pt verdana").
* @param {Element=} canvas An optional canvas element to improve performance. If not given, the function will create a new temporary canvas element.
*
* @see http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
*/
function getTextWidth(text, fontStyle, canvas) {
// if given, use cached canvas for better performance
// else, create new canvas
canvas = canvas || document.createElement("canvas");
var context = canvas.getContext("2d");
context.font = fontStyle;
var metrics = context.measureText(text);
return metrics.width;
}
/**
* Returns text whose display width does not exceed the given maxWidth.
* If the given text is too wide, it will be truncated so that text + ellipsis
* is still less than maxWidth wide.
*
* @param text The text to be truncated.
* @param {String} fontStyle The font style that the string is to be rendered with.
* @param maxWidth Max display width of string.
* @param {String=} ellipsis Set to "..." by default.
* @param {Element=} canvas Optional canvas object to improve performance.
*
*/
function truncateText(text, fontStyle, maxWidth, ellipsis, canvas) {
var width;
var len = text.length;
ellipsis = ellipsis || "...";
while ((width = getTextWidth(text, fontStyle, canvas)) > maxWidth) {
--len;
text = text.substring(0, len) + ellipsis;
}
return text;
}
这个例子:
var maxWidth = 200;
var fontStyle = "bold 12pt arial";
var text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
var truncatedText = truncateText(text, fontStyle, maxWidth)
console.log(truncatedText);
生成:“Lorem ipsum dolor sit a...”