JQuery 控制超出内容显示省略号

长度超出规定长度,显示省略号

设置class为displayPart,

设置自定义属,displayLength可显示长度(不包含...),双字节字符,长度 *2,




  1. <script type="text/javascript">  
  2.     $.fn.extend({  
  3.         displayPart:function () {  
  4.             var displayLength = 100;  
  5.             displayLength = this.attr("displayLength") || displayLength;  
  6.             var text = this.text();  
  7.             if (!text) return "";  
  8.   
  9.             var result = "";  
  10.             var count = 0;  
  11.             for (var i = 0; i < displayLength; i++) {  
  12.                 var _char = text.charAt(i);  
  13.                 if (count >= displayLength)  break;  
  14.                 if (/[^x00-xff]/.test(_char))  count++;  //双字节字符,//[u4e00-u9fa5]中文  
  15.   
  16.                 result += _char;  
  17.                 count++;  
  18.             }  
  19.             if (result.length < text.length) {  
  20.                 result += "...";  
  21.             }  
  22.             this.text(result);  
  23.         }  
  24.     });  
  25.   
  26.     $(function () {  
  27.         $(".displayPart").displayPart();  
  28.     });  
  29.   
  30. </script>  


  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  2. <html>  
  3. <head>  
  4.     <title> New Document </title>  
  5.     <meta name="Generator" content="EditPlus">  
  6.     <meta name="Author" content="">  
  7.     <meta name="Keywords" content="">  
  8.     <meta name="Description" content="">  
  9.     <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>  
  10. </head>  
  11.   
  12. <body>  
  13. <h2>hello world</h2>  
  14.   
  15. <div style="width:500px;">  
  16.       hello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello world!!!
  17. </div>  
  18.   
  19. <hr>  
  20. <h2>hello</h2>  
  21.   
  22. <div class="displayPart" displayLength="40"> hello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhelloworldhello worldhello worldhello worldhello worldhello worldhello world
  23.  
  24. </div>  
  25.   
  26.   
  27. </body>  
  28. </html>  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值