如何用除最后三个字符以外的文本填充 div

How to fill a div with text except for the last three characters

基本上,我想用一些描述性文本填充 div,这些文本可能比 div 宽度和高度可以处理的更短或更长。

我想做的是尽可能地填充div,如果文本对于div来说太多了,我想添加一个HTML … 在末尾表示内容比可见的多。

到目前为止,我一直在使用试错法计算出 div 中可以容纳多少个字符,然后使用 Left() 将字符串切割成该大小减去 3 个字符这样就有足够的 space 来在末尾附加 …

基本上,尽管有足够的 space 可以很容易地适应它,但它在中途被砍掉了,效果不太好。有没有更好的方法来做到这一点?我无法想象无论如何都可以从数学上计算出 div?

中可以容纳多少个字符

可以使用css的text-overflow: ellipsis属性来处理溢出的文字。

这是Fiddle:http://jsfiddle.net/fy1qa6o8/


备选答案:

这里是css多行文本溢出的解决方案。
Fiddle: http://jsfiddle.net/97crm7nt/1/

关于执行此操作的 Cold Fusion 函数,Regex 实际上可以对此进行非常简单的工作(我并不是说这是您需要在此处采用的方法,但在某些情况下它可能是一种有用的方法。我在图像生成中使用它。

<cfscript>
  function RELeft(string rstring,numeric num,numeric mnum = 0) {
    if (len(arguments.rstring) lte num) {
      return rstring;
    } else {
      var match = ReMatch("^(.{#arguments.mnum#,#arguments.num#}(?=\s|$)|.{#arguments.mnum#,#arguments.num#}(?=\b|))",arguments.rstring);
      return match[1];
    }
  }
</cfscript>
<cfset teststring = "this sentenc!- C.I.A. has more than 15 characters, but I only want the first 15, without breaki/ng at a word." />
<cfoutput>#teststring#<br>Left: #Left(teststring,15)#<br>RELeft: #RELeft(teststring,15)# -<br><br></cfoutput>
<cfset teststring = "Shortness." />
<cfoutput>#teststring#<br>Left: #Left(teststring,15)#<br>RELeft: #RELeft(teststring,15)#<br><br></cfoutput>
<cfset teststring = "a.b.c.d.e.f.g.h.i.j.k.l.m.n" />
<cfoutput>#teststring#<br>Left: #Left(teststring,15)#<br>RELeft: #RELeft(teststring,15,15)#<br><br></cfoutput>
<cfset teststring = "myspacebarcalledinsick" />
<cfoutput>#teststring#<br>Left: #Left(teststring,15)#<br>RELeft: #RELeft(teststring,15,13)#<br><br></cfoutput>
<cfset teststring = "a supercalifragilisticexpialidocious day." />
<cfoutput>#teststring#<br>Left: #Left(teststring,15)#<br>RELeft: #RELeft(teststring,15)#<br><br></cfoutput>
<cfset teststring = "a supercalifragilisticexpialidocious day." />
<cfoutput>#teststring#<br>Left: #Left(teststring,15)#<br>RELeft(min 4): `#RELeft("teststring",15,4)#`<br><br></cfoutput>

事实上,有些人可能想用 \b(正则表达式单词边界)来做到这一点。我选择不这样做,因为 . 是一个单词边界,你可能会被像 F.B.I. 这样的缩写绊倒。我的函数只会在绝对必要的时候匹配一个句点,比如 a.b.c.d.e.f.g.h.i.j.k.m.n.o.p..

这样的字符串

它还提供了第三个参数来设置在找到第一个 space 之前的最少字符数。您可以在最后两个示例中看到差异。