日期:2014-05-16  浏览次数:20348 次

js按宽度截取字符串。
String.prototype.getBytes = function() {   
    var totalLen = 0;     
    var charCode;  
    for (var i = 0; i < this.length; i++) {  
        charCode = this.charCodeAt(i);  
        if (charCode < 0x007f)  {     
            totalLen++;     
        } else if ((0x0080 <= charCode) && (charCode <= 0x07ff))  {     
            totalLen += 2;     
        } else if ((0x0800 <= charCode) && (charCode <= 0xffff))  {     
            totalLen += 3;   
        } else{  
            totalLen += 4;   
        }          
    }  
    return totalLen;   
};

String.prototype.subStringBytes = function(len) {
    var i = 0;
    var readBytes = 0;
    var charCode;  
    for (i = 0; i < this.length && readBytes <= len ; i++) {  
        charCode = this.charCodeAt(i);  
        if (charCode < 0x007f)  {     
        	readBytes++;     
        } else{
        	readBytes += 2;   
        }
    }
    if(i==this.length){
    	return this.substring(0, i);
    }
    return this.substring(0, i)+"...";   
};

$(function(){
	$("a.subStringBytes").each(function(){
		var len = $(this).parent().attr("offsetWidth");
		var html = $.trim($(this).text());
		var newHtml = '';
		var suffix = false;
		for(var j=0;j<html.length;j++){  
			newHtml += html.charAt(j);
		    $(this).text(newHtml);  
		    if($(this).attr("offsetWidth")>(len-70)){ 
		    	suffix = true;
		        break;  
		    }  
		} 
		if(suffix){
			newHtml += '...';
		}
		$(this).html(newHtml);
	});
	$("div.subStringBytes").each(function(){
		doSubString(this);
	});
	$("td.subStringBytes").each(function(){
		doSubString(this);
	});
	$("span.subStringBytes").each(function(){
		doSubString(this);
	});
});

function doSubString(obj){
	var len = $(obj).attr("offsetWidth");
	var html = $.trim($(this).html());
	var newHtml = '';
	var suffix = false;
	for(var j=0;j<html.length;j++){  
		newHtml += html.charAt(j); 
	    $(obj).html(newHtml);  
	    if($(obj).attr("offsetWidth")>(len-70)){ 
	    	suffix = true;
	        break;  
	    }  
	} 
	if(suffix){
		newHtml += '...';
	}
	$(obj).html(newHtml);
}