2

我需要截断侧面菜单中的字符串,以使它们适合没有换行符的 div。div 具有固定的宽度。我正在寻找一个图书馆来为我做这件事。如果字符串太长而无法放入 div,则应将其截断,如下所示:

<div>This string is too long</div>==><div>This string is...ong</div>

如您所见,字符串不仅被省略号截断,而且最后三个字母也是可见的。这是为了增加可读性。截断不应该关心空格。

有谁知道包含此类功能的库?我们在整个项目中主要使用 jQuery。

提前致谢!

4

3 回答 3

2

我不知道这样做的库本身,但是使用 HTML5 Canvas 和Canvas text metrics,您可以确定该字符串是否适合,如果不适合,您必须将其剪掉多少。

var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.font = '12pt Arial';
var metrics = context.measureText('measure me!');
var width=metrics.width;
于 2012-11-15T11:11:42.947 回答
2

一旦我使用jQuery.dotdotdot

将您的 html 视为

<div class="longtext">This string is too long</div>

使用 dotdotdot 后只需使用此 javascript

$(document).ready(function() {
    $(".longtext").dotdotdot();
});

访问他们的网站以获取更多可配置选项。

于 2012-11-15T11:16:48.327 回答
1

这个 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...”

于 2014-01-09T09:43:16.673 回答