多行文本截断问题

Multiline Text Truncation Issue

我目前有一个 jQuery 的片段,它在子字符串大于父容器时成功截断我的文本(见下文)。

var initial = $('.js-text').text();
$('.js-text').text(initial);
while($('.js-text').outerHeight() > $('.js-text-truncator').height()) {
  $('.js-text').text(function(index, text) {
    return text.replace(/\W*\s(\S)*$/, '...');
  });
}

我已经使用了我所拥有的语义,因为我计划在现有标记的多个地方使用这个 jQuery 小组件,如下所示:

<div class="existing-first-div-container js-text-truncator">
  <p class="existing-first-string js-text">The quick brown fox</p>
</div>
<div class="existing-second-div-container js-text-truncator">
  <p class="existing-second-string js-text"> jumped over the lazy red dog.</p>
</div>

如果您已经读到这里并且已经猜到了我的问题,顺便说一句...

所以问题是我的 jQuery 正在存储文本,但它存储了 所有 文本。因此,这两个现有的 div 都被截断了,但都以 "The quick brown fox jumped over the lazy red dog." 而不是第一个读数 "The quick brown fox" 和第二个读数“跳过了懒惰的红狗”。

是否可以按照我想要的方式使用我的 js-text-truncator 作为我的标记的扩展,而不是一次存储所有截断的文本实例?

.text 明确指出

Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.

一旦你有了包含 .js-text 的元素集,对它们执行 .each,然后获取、t运行 分类并分别设置 .text

如果你想让它在 window 重新调整大小时重新 运行,我建议你通过超时来完成它(所以代码 运行s 在window 停止调整大小至少 400 毫秒)。如果没有这个解决方法,它往往会对性能产生很大的影响。

var resizeTimeout = false;
$(window).resize(onWindowResize); // bind resize event.

trimAllText(); //run once at start.

function onWindowResize() {
    if(resizeTimeout){
        clearTimeout(resizeTimeout);
    }
    resizeTimeout = setTimeout(function(e){ 
        resizeTimeout = false; 

        // this is code that is ran at the "end" of a resize.
        trimAllText();
    }, 400);
}

function trimAllText(){
  var initialElements = $('.js-text');
  initialElements.each(function(){
    var elem = $(this);
    while(elem.outerHeight() > elem.closest('.js-text-truncator').height()) {
      elem.text(function(index, text) {
        return text.replace(/\W*\s(\S)*$/, '...');
      });
    });
  });
}