截断文本 通用jQuery插件 Ttruncate.js

  • 源码大小:23.34KB
  • 所需积分:1积分
  • 源码编号:19JP-3137
  • 浏览次数:785次
  • 最后更新:2023年05月09日
  • 所属栏目:文本
我要下载
加入收藏
本站默认解压密码:19jp.com 或 19jp_com

简介

一个轻量级且灵活的JavaScript/jQuery插件,允许您根据指定的行数截断网页上的文本内容。

它提供了在开头、中间或结尾截断文本的选项,允许您为内容选择最合适的方法。

如何使用它:

1.将Truncate.js脚本添加到HTML页面中。jQuery是可选的。

  1. <!-- jQuery is OPTIONAL -->
  2. <script src="/path/to/cdn/jquery.min.js"></script>
  3.  
  4. <!-- jQuery is OPTIONAL -->
  5. <script src="/path/to/dist/truncate.min.js"></script>

2.在您的长文本内容上初始化插件。在下面的示例中,元素中带有类“demo”的文本将被截断为3行,截断发生在文本的中间。将添加省略号以表示截断。

  1. <div class="demo">
  2. Your Content Here
  3. </div>
  1. // As a jQuery plugin
  2. $('#demo').truncate({
  3. lines: 3, // default: 1
  4. position: 'middle', // default 'end'
  5. });
  6.  
  7. // Vanilla JS
  8. const truncated = new Truncate(document.getElementById('#demo'), {
  9. lines: 3,
  10. position: 'middle',
  11. });

3.更多插件选项。

  1. $('#demo').truncate({
  2.  
  3. // set the string to indicate that the text has been truncated
  4. ellipsis: '…',
  5.  
  6. // show more/less text
  7. showMore: '',
  8. showLess: '',
  9. // line height in px
  10. lineHeight: 'auto',
  11.  
  12. // truncate the text to fit in the specified height
  13. maxHeight: undefined,
  14. });

4.API方法。

  1. // jQuery
  2. // Update the HTML and truncate.
  3. $('#demo').truncate('update', 'new content to truncate');
  4.  
  5. // expand the content
  6. $('#truncate_me').truncate('expand');
  7.  
  8. // collapse the content
  9. $('#truncate_me').truncate('collapse');
  1. // Vanilla JS
  2. // Update the HTML and truncate.
  3. truncated.truncate('update', 'new content to truncate');
  4.  
  5. // expand the content
  6. truncated.truncate('expand');
  7.  
  8. // collapse the content
  9. truncated.truncate('collapse');
  10.  
  11. // check if is truncated
  12. truncated.isTruncated;
  13.  
  14. // check if is collapsed
  15. truncated.isCollapsed

预览截图