文本溢出省略号:避免单词中断

时间:2012-10-22 13:45:43

标签: css css3

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

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

省略号正在运行,问题是它会删除最后一个单词,我希望它将省略号(...)放在一个完整单词的最后。

例如,如果我有文本:“stackoverflow是最好的”,并且如果它需要在结尾附近切割,我希望它显示“stackoverflow是...”而不是“stackoverflow是......“

3 个答案:

答案 0 :(得分:5)

我担心这是不可能的。有一次text-overflow: ellipsis-word,这可以做到这一点,但它没有在浏览器中实现,它已从CSS3草稿中删除。

答案 1 :(得分:2)

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

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>

答案 2 :(得分:0)

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

它也适用于多行文本,并且如果文本重排,则可以适应性地进行调整。如果屏幕尺寸发生变化它还包括路径名的智能截断,例如http://example.com/some/long/.../path.html


请注意在宽度发生变化或插件可能无法预期的方式不可用的情况下出现基于宽度的计时问题,例如文本最初是隐藏的还是更改了字体(例如,加载网络字体)一些浏览器)。可能需要重新应用或在此类更改后应用。

但99%的情况下,该插件似乎快速而强大。

相关问题