我为这个问题做了一个图像,以使它更容易理解。
是否可以在具有固定宽度和多行的<div>上创建省略号?

我到处尝试了一些jQuery插件,但找不到我想要的那个。有什么建议吗?想法?
发布于 2017-12-15 00:07:16
在我的场景中,我无法使用上面提到的任何函数,而且我还需要告诉函数显示多少行,而不管字体大小或容器大小。
我的解决方案基于Canvas.measureText方法(这是一个HTML5特性)的使用,正如Domi在here中所解释的那样,所以它不是完全跨浏览器的。
你可以看到它是如何在this fiddle上工作的。
代码如下:
var processTexts = function processTexts($dom) {
var canvas = processTexts .canvas || (processTexts .canvas = document.createElement("canvas"));
$dom.find('.block-with-ellipsis').each(function (idx, ctrl) {
var currentLineAdded = false;
var $this = $(ctrl);
var font = $this.css('font-family').split(",")[0]; //This worked for me so far, but it is not always so easy.
var fontWeight = $(this).css('font-weight');
var fontSize = $(this).css('font-size');
var fullFont = fontWeight + " " + fontSize + " " + font;
// re-use canvas object for better performance
var context = canvas.getContext("2d");
context.font = fullFont;
var widthOfContainer = $this.width();
var text = $.trim(ctrl.innerHTML);
var words = text.split(" ");
var lines = [];
//Number of lines to span over, this could be calculated/obtained some other way.
var lineCount = $this.data('line-count');
var currentLine = words[0];
var processing = "";
var isProcessing = true;
var metrics = context.measureText(text);
var processingWidth = metrics.width;
if (processingWidth > widthOfContainer) {
for (var i = 1; i < words.length && isProcessing; i++) {
currentLineAdded = false;
processing = currentLine + " " + words[i];
metrics = context.measureText(processing);
processingWidth = metrics.width;
if (processingWidth <= widthOfContainer) {
currentLine = processing;
} else {
if (lines.length < lineCount - 1) {
lines.push(currentLine);
currentLine = words[i];
currentLineAdded = true;
} else {
processing = currentLine + "...";
metrics = context.measureText(processing);
processingWidth = metrics.width;
if (processingWidth <= widthOfContainer) {
currentLine = processing;
} else {
currentLine = currentLine.slice(0, -3) + "...";
}
lines.push(currentLine);
isProcessing = false;
currentLineAdded = true;
}
}
}
if (!currentLineAdded)
lines.push(currentLine);
ctrl.innerHTML = lines.join(" ");
}
});
};
(function () {
$(document).ready(function () {
processTexts($(document));
});
})();使用它的HTML将如下所示:
<div class="block-with-ellipsis" data-line-count="2">
VERY LONG TEXT THAT I WANT TO BREAK IN LINES. VERY LONG TEXT THAT I WANT TO BREAK IN LINES.
</div>获取font-family的代码相当简单,在我的例子中可以工作,但是对于更复杂的场景,您可能需要使用these lines中的一些东西。
此外,在我的例子中,我告诉函数要使用多少行,但您可以根据容器的大小和字体来计算要显示的行数。
https://stackoverflow.com/questions/3404508
复制相似问题