jquery-trim.js

String.prototype.mylength = function(){
  var arr = this.match(/[\u00FF-\uFFFF]/gi);
  if(!arr || arr==null)
      return this.length;
  var len = this.length + arr.length;
  return len;
}

String.prototype.mysubstring = function(limit){
  var len = 0;
  var arr = [];
  for(var i=0;i<this.length;i++){
    var it = this.substring(i,i+1);
    len += it.mylength();
    if(len > limit)
        break;
    arr[arr.length] = it;
  }

  var result = arr.join("");
  return result;
}

jQuery.fn.limit = function(){
  $(this).each(function(){
    
    var mylimit = parseInt($(this).attr("limit"));
    var applied = $(this).attr("applied");
    if(applied)
        return;
    var text = $(this).text();
    var original_text = text;
    if(text.mylength() > mylimit){
      text = text.mysubstring(mylimit);
      text += "…";
      text = "<SPAN style=\"position:relative\"><SPAN class=’tooltip’>" + original_text + "</SPAN>" + text + "</SPAN>";
      $(this).html(text);
      $(this).mouseover(function(){
            $(this).find(".tooltip").css("display","");
          });
      $(this).mouseout(function(){
            $(this).find(".tooltip").css("display","none");
          });
      $(this).find(".tooltip")
          .css({ ‘display’:'block’,
                 ‘position’:'absolute’,
                 ‘top’:'2em’,
                 ‘left’:'2em’,
                 ‘width’:'15em’,
                 ‘border’:'1px solid #0cf’,
                 ‘background-color’:'#cff’,
                 ‘color’:'#000′,
                 ‘text-align’:'center’,
                 ‘word-wrap’:'break-word’,
                 ‘word-break’:'break-all’})
          .css("display","none");
      $(this).attr("applied",true);
    }
  
  });
}

function apply_limit(){
  $("[@limit]").limit();
}

$(document).ready(apply_limit);

html中这样用:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<SCRIPT LANGUAGE="JavaScript" src="jquery.js"></SCRIPT>
<SCRIPT LANGUAGE="JavaScript" src="jquery-trim.js"></SCRIPT>
</HEAD>

<BODY>
这是一行 <br><br>
这是另一行 <span limit="8">这是超级长昂昂昂昂昂昂昂昂昂昂昂的字符串</span>
</BODY>
</HTML>

抓图:

注意到html中<span limit="8">了吗? 后面的文字按“中文两个字符,英文一个字符”的规则截断了,随后只显示…,鼠标移上去,出现完整信息的提示。


评论

该日志第一篇评论

发表评论

评论也有版权!