简体   繁体   English

根据JavaScript中的长度截断多行文本

[英]Truncate multiple lines of text based on length in JavaScript

I have the following JavaScript code to truncate a string based on its length and add "..." at the end. 我有以下JavaScript代码根据其长度截断字符串,并在末尾添加“ ...”。

var elem = document.createElement('lengthDiv');
var text = "text to truncate";
elem.style.position = "absolute";
elem.style.whiteSpace = "nowrap";
elem.style.font = "helvetica";
elem.innerHTML = text;
document.documentElement.appendChild(elem);
var length = elem.clientWidth;
if (length > 298) {
    var i = 1;
    elem.innerHTML = '';
    while (elem.clientWidth < 298 && i < text.length) {
        elem.innerHTML = text.substr(0, i) + '...';
        i++;
    }
}
if (elem.clientWidth < 298 && i > 1) {
    while (elem.clientWidth < 298) {
        elem.innerHTML = elem.innerHTML + '.';
    }
}
var endresult = elem.innerHTML;

How do I make this code work for a single block of text where it will affect multiple lines of text? 如何使此代码适用于单个文本块,从而影响多行文本? For example, I want to turn this: 例如,我想转一下:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Into this (roughly): 对此(大致):

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed... 
Ut enim ad minim veniam, quis nostrud exercitation ullamco l...
Duis aute irure dolor in reprehenderit in voluptate velit es...
Excepteur sint occaecat cupidatat non proident, sunt in culp...

I need it to be with only JavaScript , no JQuery or any other libraries. 我需要只有JavaScript ,没有JQuery或任何其他库。

I'd split your string and then truncate each item in that array. 我将拆分字符串,然后截断该数组中的每个项目。 That would give you truncated sentences. 那会给你删减句子。

var res = text.split(".");

for (i = 0; i < res.length; i++) { 
        // truncate each sentence
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM