截断div内的文本 [英] Truncating text inside a div

查看:106
本文介绍了截断div内的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些文字是动态的(来自我的数据库),我需要将它放入我的div中。

我的div有固定的大小,但是当文本变长时会分成两行。如果文本太长,我想在最后加上三个点,以便使它适合在一行内。



例如 My真的很长的文本变成我真的很... ...



,但基本上所有这些都依赖于以某种方式计算字符。这并不是真的幸运,因为角色没有固定的宽度。例如,一个大写字母W比一个小字母i宽得多。

因此,我在字符计数方法中遇到了两个问题:


  1. 如果文本有许多窄字符,它会被剪切并附加...,即使文本实际上可以放在一行上,即使是原始形式也是如此。 p>


  2. 文本包含很多宽字符,即使将其裁剪为最大字符数并添加点后,该文本也会在两行中结束。


这里有什么解决方案(JavaScript或css?)考虑到文本的实际宽度,而不是字符?

解决方案

使用这些样式:

  white-space:nowrap; / *保持文本在一行* / 
溢出:隐藏; / *防止文本显示在边界之外* /
文本溢出:省略号; / *用省略号截断文本* /


I have some text that is dynamic (comes from my database) that I need to fit into my div.

My div have a fixed size, but when the text becomes to long goes into two lines. If the text is to long, I would like to put three dots at the end to make it fit inside one line.

So for example My really long text becomes My really lo...

I have tried several attempts, but basically all of them depends on counting characters in some way. That is not really fortunate, since a character does not have a fixed width. For example a capital W is much wider than an small i.

Therefore I get two 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 even in it's original form.

  2. The text contains many wide characters, and it ends up on two lines even after I cut it to the max number of chars and appending the dots.

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

解决方案

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*/

这篇关于截断div内的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆