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

16
在我的网页中,我有一个带有固定宽度的div,并使用以下CSS:
width: 200px; 
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;

省略号已经起作用了,问题在于它会截断最后一个单词,我希望它能在完整的一个单词的结尾处放置省略号(...)。

例如,如果我的文本是:"stackoverflow is the best",并且如果它需要在接近结尾的位置被截断,我希望它显示为 "stackoverflow is the ..." 而不是 "stackoverflow is the be..."。

4个回答

6
当然可以。(只要你愿意稍微改变一下你的标记语言。)

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>

那段代码没有将一个超出边界的长单词省略。所以如果你想要这样做,就把每个单词都包裹在另一个 span 中(每个单词内部有两个 span),并添加这段代码: - Hunter Perrin
.foo > span > span { /* 如果你想要一个巨大单词的省略号,你必须使用两个span */ display: inline-block; max-width: 100%; overflow: hidden; } .foo > span { max-width: 100%; ... [其余代码] - Hunter Perrin
1
我很欣赏那些能够找到“不可能”问题解决方案的人。 - aero
1
这太棒了。它运行得很好,正是我一直在寻找的东西。它让我能够做两件事:1)具有“text-overflow: ellipsis”效果而不会打断单词,以及(2)在span的开头放置逗号,使单词列表不以“,...”结束。太棒了。谢谢。 - Timothy Zorn

6

很抱歉,这是不可能的。曾经有一个text-overflow: ellipsis-word属性可以实现这个功能,但它没有被浏览器实现,并且在CSS3草案中已经被删除。


0

有一个名为dotdotdot的jQuery插件可以实现这个功能。

它也适用于多行文本,并且会根据文本重新流动(例如屏幕尺寸更改)而自适应。它还包括智能截断路径名,例如http://example.com/some/long/.../path.html


请注意,在宽度发生变化或以插件可能不期望的方式不可用的情况下,例如如果文本最初被隐藏或者更改字体(例如在某些浏览器上加载Web字体),可能会出现基于宽度的时间问题。在此类更改后可能需要重新应用或应用。

但99%的时间,该插件似乎快速且稳健。


0
如果您想显示一行以省略号结尾的文本,例如新闻滚动条,只需执行以下操作:
p { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接