窗口大小上的多行文本截断

时间:2015-10-10 14:38:51

标签: javascript jquery text truncation

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

我需要我的双线描述blurb才能响应,因为当调整浏览器大小时文本会重新响应。下面的示例成功收缩字符串的大小,并在缩小浏览器时替换为省略号。但是当您扩展浏览器时,字符串不会展开

所以简而言之,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)*$/, '...');
    });
}
});

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

如果有人有答案,我会非常感激。

1 个答案:

答案 0 :(得分:2)

如果您想修复解决方案,您必须存储初始文本并在进行任何修改之前将其设置到div中。剪切文本的某些部分后,由于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,所以我希望它能帮到你。