Jquery - 逐行截断文本(不是字符数) [英] Jquery - Truncate Text by Line (not by character count)

查看:89
本文介绍了Jquery - 逐行截断文本(不是字符数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个Jquery脚本来逐行截断文本(而不是字符数)。

I need a Jquery script to truncate a text paragraph by line (not by character count).

我想实现一个均匀截断的文本块。它应该有一个更多和更少的链接来扩展和缩短文本段落。我的文本段落包含在一个带有类的div中,如下所示:

I would like to achieve an evenly truncated text-block. It should have a "more" and "less" link to expand and shorten the text paragraph. My text paragraph is wrapped in a div with a class, like this:

<div class="content">
<h2>Headline</h2>
<p>The paragraph Text here</p>
</div>

我可以在SOF上找到的最接近的解决方案是下面的解决方案(但它适用于textarea元素和对我来说不起作用):
限制textarea中的行数

The closest solution i could find on SOF is the one below (but it`s for textarea element and does not work for me): Limiting number of lines in textarea

非常感谢任何提示。
Ben

Many thanks for any tips. Ben

推荐答案

对于基本方法,您可以查看行 - height CSS属性并在计算中使用它。请记住,这种方法不会考虑大于该高度的其他内联元素(例如图像)。

For a basic approach, you could take a look at the line-height CSS property and use that in your calculations. Bear in mind that this approach will not account for other inline elements that are larger than that height (e.g. images).

如果你想要更高级的东西,你可以使用 getClientRects()函数获取有关每一行的信息。此函数返回 TextRectangle 对象的集合,每个对象具有宽度,高度和偏移量。

If you want something a bit more advanced, you can get the information about each line using getClientRects() function. This function returns a collection of TextRectangle objects with width, height and offset for each one.

参见这个答案 getClientRects()如何运作的示例(尽管是一个无关的目标)。

See this answer here for an example (albeit an unrelated goal) of how getClientRects() works.



更新,有一点时间回来并用一个实际的例子更新这个答案。这是基本的,但你明白了:


Update, had a bit of time to come back and update this answer with an actual example. It's basic, but you get the idea:

http: //jsbin.com/ukaqu3/2

一些指示:


  • getClientRects 返回的集合是静态的,如果包含元素的尺寸发生变化,它将不会自动更新。我的示例通过捕获窗口的resize事件来解决这个问题。

  • The collection returned by getClientRects is static, it won't update automatically if the containing element's dimensions change. My example works around this by capturing the window's resize event.

对于我不理解的一些奇怪的标准兼容性原因,您调用 getClientRects 的元素必须是内联元素。在我的示例中,我使用容器div与另一个div中的文本,其中 display:inline

For some strange standards-compliance reason that I'm not understanding, the element you call getClientRects on must be an inline element. In the example I have, I use a container div with the text in another div inside with display: inline.

这篇关于Jquery - 逐行截断文本(不是字符数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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