Html 截断div内的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15405817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 06:26:45  来源:igfitidea点击:

Truncating text inside a div

javascripthtmlcss

提问by ?yvind Br?then

I have some dynamic text (comes from a database) and I need to fit into a div

我有一些动态文本(来自数据库),我需要适应 div

My divhas a fixed size. However, when the text becomes too long, it breaks into two lines. I would like to put three dots at the end of longer texts to make them fit inside a single line.

我的div有固定尺寸。但是,当文本变得太长时,它会分成两行。我想在较长文本的末尾放置三个点,以使它们适合一行。

For example: My really long textbecomes My really lo...

例如:My really long text变成My really lo...

I have committed several attempts, but basically all of them depend on counting characters. That is, whatsoever, not really fortunate, for characters do not have a fixed width. For example, a capital Wis much wider than an small i

我进行了几次尝试,但基本上所有尝试都依赖于计数字符。也就是说,无论如何,并不是很幸运,因为字符没有固定的宽度。例如,一个资本W比一个小i

Therefore, I encounter two main problems with the character-counting approach:

因此,我在使用字符计数方法时遇到了两个主要问题:

  1. If the text has many narrow characters, it gets cut and appended with ..., even if the text would actually fit on one line afore trimmed.

  2. When the text contains many wide characters, it ends up on two lines even after I cut it to the maximum number of characters and append the dots.

  1. 如果文本有许多窄字符,它会被剪切并附加...,即使文本在修剪前实际上适合一行。

  2. 当文本包含许多宽字符时,即使我将其剪切到最大字符数并附加点,它也会以两行结尾。

Is there any solution here (JavaScript or CSS) that takes the actual width of the text into consideration, and not the number of characters?

这里是否有任何解决方案(JavaScript 或 CSS)考虑文本的实际宽度,而不是字符数?

回答by James Coyle

Use these styles:

使用这些样式:

white-space: nowrap;      /*keep text on one line */
overflow: hidden;         /*prevent text from being shown outside the border */
text-overflow: ellipsis;  /*cut off text with an ellipsis*/

回答by Ryan McDonough

I would suggest Trunk8

我建议Trunk8

You can then make any text fit to the size of the div, it trims the text that would cause it to go beyond 1 line (options are available to set amount of lines allowed)

然后,您可以使任何文本适合 div 的大小,它会修剪会导致其超过 1 行的文本(可以使用选项来设置允许的行数)

E.g

例如

$('.truncate').trunk8();

回答by Shouvik

Apart from ellipsis, I would suggest display the whole text on mouse hover using tooltip.

此外ellipsis,我建议在鼠标悬停时使用tooltip.

fiddle

小提琴

回答by Kev