Javascript 如果超过设置的宽度,在 div 中切断文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5707420/
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-23 18:32:41  来源:igfitidea点击:

Cut off text in a div if it exceeds set width?

javascriptcssxhtmltexthtml

提问by dannymcc

On a website I am working on users can add a heading to a section of a page.A simple example:

在我正在处理的网站上,用户可以向页面的某个部分添加标题。一个简单的例子:

M11-001 - loss of container and goods from Manchester

With some headings the content can be quite in-depth. In reality, for the heading at least, this content isn't always needed. The first few words would suffice to differentiate between records.

使用一些标题,内容可以非常深入。实际上,至少对于标题而言,并不总是需要这些内容。前几个词足以区分记录。

I could just set overflow:hidden to the div and ruthlessly cut of anything outside of the set width.

我可以设置 overflow:hidden 到 div 并无情地切割超出设置宽度的任何东西。

I would prefer to add ... To the end. Like so:

我宁愿添加......到最后。像这样:

M11-001 - loss of container...

So three full-stops would be added after either X width or X characters.

因此,将在 X 宽度或 X 字符之后添加三个句号。

Is this possible with CSS, or maybe JavaScript?

这可以用 CSS 还是 JavaScript 实现?

回答by NakedBrunch

Something like this? http://www.quirksmode.org/css/textoverflow.html

像这样的东西?http://www.quirksmode.org/css/textoverflow.html

Text-Overflow

文本溢出

The text-overflow declaration allows you to deal with clipped text: that is, text that does not fit into its box. The ellipsis value causes three periods to be appended to the text.

text-overflow 声明允许您处理剪切文本:即不适合其框的文本。省略号值导致将三个句点附加到文本中。