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

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

简介

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

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

如何使用它:

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

<!-- jQuery is OPTIONAL -->
<script src="/path/to/cdn/jquery.min.js"></script>

<!-- jQuery is OPTIONAL -->
<script src="/path/to/dist/truncate.min.js"></script>

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

<div class="demo">
  Your Content Here
</div>
// As a jQuery plugin
$('#demo').truncate({
  lines: 3, // default: 1
  position: 'middle', // default 'end'
});

// Vanilla JS 
const truncated = new Truncate(document.getElementById('#demo'), {
  lines: 3,
  position: 'middle',
});

3.更多插件选项。

$('#demo').truncate({

  // set the string to indicate that the text has been truncated
  ellipsis: '…',

  // show more/less text
  showMore: '',
  showLess: '',
  
  // line height in px
  lineHeight: 'auto',

  // truncate the text to fit in the specified height
  maxHeight: undefined,
  
});

4.API方法。

// jQuery
// Update the HTML and truncate.
$('#demo').truncate('update', 'new content to truncate');

// expand the content
$('#truncate_me').truncate('expand');

// collapse the content
$('#truncate_me').truncate('collapse');
// Vanilla JS 
// Update the HTML and truncate.
truncated.truncate('update', 'new content to truncate');

// expand the content
truncated.truncate('expand');

// collapse the content
truncated.truncate('collapse');

// check if is truncated
truncated.isTruncated;

// check if is collapsed
truncated.isCollapsed

预览截图