【问题标题】:Multiline Text Truncation on Window Resize窗口调整大小时的多行文本截断
【发布时间】:2015-10-10 14:38:50
【问题描述】:

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

当调整浏览器大小时,我需要我的双线描述简介在文本重排时做出响应。我下面的示例成功收缩字符串的大小,并在缩小浏览器时用省略号替换。但是当您扩大浏览器时,字符串不会扩展

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

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

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

【问题讨论】:

    标签: javascript jquery text truncation


    【解决方案1】:

    如果您想修复您的解决方案,您必须在进行任何修改之前存储初始文本并将其设置到您的 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)*$/, '...');
                });
            }
        });
    });
    

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

    【讨论】:

    • 谢谢。 js解决方案奏效了。我也会看看css解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 2011-02-28
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多