Window 调整大小时多行文本截断

Multiline Text Truncation on Window Resize

我正在编写我的 jQuery 应用程序,但遇到了障碍。

我需要我的双行描述简介在调整浏览器大小时响应文本重排。我在下面的示例成功地 收缩了 字符串的大小,并在您缩小浏览器时将其替换为省略号。但是当你扩大浏览器时,字符串不会 expand

简而言之——jQuery 是在浏览器调整大小(变小)时削减文本,但不会在浏览器调整大小(变大)时将文本添加回去。

当浏览器变大时,我真的需要重新添加文本。

这是标记:

<!-- html -->
<div class="description-container">
  <span class="description-blurb">When France decided to participate in the
  International Geophysical Year by sending teams to Antarctica, it did lorem
  ipsum dolor amet this text will be truncated or else I will be very, very
  upset inside.</span>
</div>

Sass 如果你觉得你需要它(不确定是否有必要回答这个问题):

// Sass
.feature .description-container {
  @include box-sizing;
  height: 1.875rem;
  width: 100%;
  margin-top: 3.125rem;
  margin-bottom: 1.25rem;
  color: $light-grey;
  font-size: .6875rem;
  font-weight: 200;
  line-height: 1rem; // revisit this value
}
.feature .content-shadow {
  height: .1875rem;
  width: 100%;
  @include linear-gradient(rgba(0, 0, 0, .1), transparent);
  margin-bottom: .4375rem;
}

这是脚本:

// jQuery
while($('.description-blurb').outerHeight() > $('.description-container').height()) {
    $('.description-blurb').text(function(index, text) {
        return text.replace(/\W*\s(\S)*$/, '...');
    });
}
$(window).resize(function() {
while($('.description-blurb').outerHeight() > $('.description-container').height()) {
    $('.description-blurb').text(function(index, text) {
        return text.replace(/\W*\s(\S)*$/, '...');
    });
}
});

我试图通过寻找答案来尊重每个人的时间。但是我没有运气:(

如果有人有答案,我将不胜感激。

如果您想修复您的解决方案,您必须在任何修改之前存储初始文本并将其设置到您的 div 中。剪切部分文本后,您无法 return 将其还原,因为您的 html 元素不再包含它。所以修复你的解决方案:

$(function () {
    var initial = $('.description-blurb').text();

    $('.description-blurb').text(initial);
    while($('.description-blurb').outerHeight() > $('.description-container').height()) {
        $('.description-blurb').text(function(index, text) {
            return text.replace(/\W*\s(\S)*$/, '...');
        });
    }

    $(window).resize(function() {
        $('.description-blurb').text(initial);
        while($('.description-blurb').outerHeight() > $('.description-container').height()) {
            $('.description-blurb').text(function(index, text) {
                return text.replace(/\W*\s(\S)*$/, '...');
            });
        }
    });
});

此示例必须有效,但我强烈建议您检查文本溢出 CSS-属性。将它用于多行文本有点棘手,但这个 comprehensible article 有助于理解该技术。作者还加了一个Saas mixin 希望对大家有帮助