html - 将文本限制为 X 行,但调整宽度以显示所有内容

标签 html css

我看到一些解决方案使用 text-overflow:ellipsis 来显示几行文本,如果不适合则以“...”结尾。但是,我正在寻找一种 CSS 或 JS 解决方案,其中您将具有固定的高度(或行数)并且容器的宽度自然地适应以显示全文内容。

如果有必要,我可以做一些图片来更好地解释我需要什么。

希望有解决方案!

最佳答案

这将是一个粗略的形式。

let quotes = [
      'I do not regret one professional enemy I have made. Any actor who doesn\'t dare to make an enemy should get out of the business.',
      'A man thinks that by mouthing hard words he understands hard things.',
      'To say that a man is made up of certain chemical elements is a satisfactory description only for those who intend to use him as a fertilizer.',
      'Security is a kind of death.',
      'The worst loneliness is not to be comfortable with yourself.',
      'The fact is, sometimes it\'s hard to walk in a single woman\'s shoes. That\'s why we need really special ones now and then to make the walk a little more fun.',
      'Behind the phony tinsel of Hollywood lies the real tinsel.'
    ],
    rows = 3,
    quote, lastQuote,
    $quote = $('.quote'),
    getDifferentQuote = function() {
      quote = quotes[Math.floor(Math.random() * quotes.length)];
      if (quote === lastQuote) {
        return getDifferentQuote();
      } else {
        lastQuote = quote;
        return quote;
      }
    },
    changeQuote = function() {
      quote = getDifferentQuote();
      let item = $('<span />', {
        text : quote,
        class: 'tester'
      });
      item.appendTo($('body'));
      let desiredHeight = item.height() * rows;
      item.css({
        whiteSpace: 'normal',
        width     : 30 + 'px'
      });
  
      while (item.height() > desiredHeight) {
        item.css({width: (item.width() + 1) + 'px'});
      }
      $quote.css({width: item.width() + 'px'});
      $quote.text(item.text());
      item.remove();
    };
$('button').on('click', changeQuote);
$(window).load(changeQuote);
.holder {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 30px;
  background-color: #f5f5f5;
  min-height: 100px;
}
.quote {
  text-align: center;
}
.tester {
  position: absolute;
  white-space: nowrap;
  display: block;
  opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="holder">
  <div class="quote"></div>
</div>
<button>Change quote</button>

  • 选择一个随机引用,将其作为不可见项附加到正文中,最初有 1 行,
  • 通过将其高度乘以 nr 来计算所需的高度。行数(本例中为 3 行),
  • 使它变得非常窄,当它的高度大于所需的高度时,继续增加宽度。
  • 当达到所需高度时,将其内容复制到“面板”中的元素并删除不可见的元素。

当然,先决条件是确保不可见项具有相同的line-heightfont-sizeletter-spacing 作为我要用于显示的代码,在我的例子中是这样,因为我没有对它们中的任何一个进行样式设置。此外,如果显示元素有填充,则不可见的元素也需要相同,否则您应该在计算时考虑它。

Hackish,但它有效。有问题吗?

作为旁注,我上面描述的是在 changeQuote() 函数中。其余的只是 helper (添加引号以包含各种长度的文本,一个确保引号不会重复的功能和其他细节 - 你不需要这些东西的大部分)。

还有一点要注意:如果您是来这里学习的,您可能会发现我所做的有用。如果你来这里是为了完成工作,那你就上错网站了,恕我直言。正确的做法是聘请专业人士。


为了理解我为什么要使用不可见的元素来执行此操作:即使它非常快(比我预期的要快),如果我在一个可见的元素上执行此操作,理论上它可能会导致渲染其中间状态的一瞥。让我们做一个测试,让不可见的元素可见:

let quotes = [
      'I do not regret one professional enemy I have made. Any actor who doesn\'t dare to make an enemy should get out of the business.',
      'A man thinks that by mouthing hard words he understands hard things.',
      'To say that a man is made up of certain chemical elements is a satisfactory description only for those who intend to use him as a fertilizer.',
      'Security is a kind of death.',
      'The worst loneliness is not to be comfortable with yourself.',
      'The fact is, sometimes it\'s hard to walk in a single woman\'s shoes. That\'s why we need really special ones now and then to make the walk a little more fun.',
      'Behind the phony tinsel of Hollywood lies the real tinsel.'
    ],
    rows = 3,
    quote, lastQuote,
    $quote = $('.quote'),
    getDifferentQuote = function() {
      quote = quotes[Math.floor(Math.random() * quotes.length)];
      if (quote === lastQuote) {
        return getDifferentQuote();
      } else {
        lastQuote = quote;
        return quote;
      }
    },
    changeQuote = function() {
      quote = getDifferentQuote();
      let item = $('<span />', {
        text : quote,
        class: 'tester'
      });
      item.appendTo($('body'));
      let desiredHeight = item.height() * rows;
      item.css({
        whiteSpace: 'normal',
        width     : 30 + 'px'
      });
  
      while (item.height() > desiredHeight) {
        item.css({width: (item.width() + 1) + 'px'});
      }
      $quote.css({width: item.width() + 'px'});
      $quote.text(item.text());
      item.remove();
    };
$('button').on('click', changeQuote);
$(window).load(changeQuote);
.holder {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 30px;
  background-color: #f5f5f5;
  min-height: 100px;
}
.quote {
  text-align: center;
}
.tester {
  position: absolute;
  white-space: nowrap;
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="holder">
  <div class="quote"></div>
</div>
<button>Change quote</button>

它永远不会出现。它应该出现在按钮下方,但从未呈现。至少不在我的机器上。很酷。

关于html - 将文本限制为 X 行,但调整宽度以显示所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44377400/

相关文章:

html - webkit 浏览器 a :active changing size from a

JavaScript:当文本位于文本区域内时,所选文本不会被替换

javascript - PushState 在不应该执行的时候执行

html - 使用 Bootstrap,如何根据断点将 div 放在不同的行中?

javascript - 如何使 x 轴刻度线跨越整个条形图?

css - Bootstrap 选择未显示

html - 添加 anchor 标记后,图标不会在悬停时改变颜色。

html - 当鼠标悬停在按钮上时,下拉菜单不显示

jquery - 呈现数据表 bool 列

javascript - Bootstrap Carousel 在 Chrome 中不工作