16

在我的网页中,我有一个固定宽度的 div 并使用以下 css:

width: 200px; 
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;

省略号是有效的,问题是它削减了最后一个单词,我希望它把省略号 (...) 放在一个完整单词的最后。

例如,如果我有文本:“stackoverflow 是最好的”,并且如果它需要在接近尾声时被剪切,我希望它显示“stackoverflow 是...”而不是“stackoverflow 是... "

4

3 回答 3

6

恐怕这是不可能的。曾经有text-overflow: ellipsis-word,它可以做到这一点,但它没有在浏览器中实现,并且从 CSS3 草案中删除。

于 2012-10-22T16:03:20.403 回答
5

当然有可能。(如果你愿意稍微改变你的标记。)

https://jsfiddle.net/warphLcr/

<style>
  .foo {
    /* Make it easy to see where the cutoff point is */
    border: 2px solid #999;

    padding-right: 18px; /* Always have room for an ellipsis */
    width: 120px;
    height: 1.1em; /* Only allow one line of text */
    overflow: hidden; /* Hide all the text below that line */
    background-color: #fff; /* Background color is required */
  }
  .foo > span {
    display: inline-block; /* These have to be inline block to wrap correctly */
    position: relative; /* Give the ellipsis an anchor point so it's positioned after the word */
    background-color: #fff; /* Cover the ellipsis of the previous word with the same background color */
    white-space: pre; /* Make sure the only point where wrapping is allowed is after a whole word */
  }
  .foo > span:after {
    position: absolute; /* Take the ellipsis out of the flow, so the next item will cover it */
    content: "…"; /* Each span has an ellipsis */
  }
  .foo > span:last-child:after {
    content: ""; /* Except for the last one */
  }
</style>

<div class="foo">
  <!-- These *must not* have white space between them, or it will collapse to a space before the next word, and the ellipsis will become visible -->
  <span>stackoverflow</span><span> is</span><span> the</span><span> best</span>
</div>
于 2016-11-18T02:48:15.370 回答
0

有一个 jQuery 插件可以做到这一点,称为dotdotdot

它也适用于多行文本,并在文本重排时做出响应,例如屏幕大小发生变化。它还包括路径名的智能截断,例如http://example.com/some/long/.../path.html


请注意在宽度更改或以插件可能未预料到的方式变得不可用的情况下,基于宽度的计时问题的可能性,例如文本最初隐藏或更改字体(例如在某些浏览器上加载 Web 字体) . 可能需要重新申请或在此类更改后被申请。

但在 99% 的情况下,该插件看起来既快速又健壮。

于 2014-09-15T12:07:56.217 回答