js效果,将table中多余的内容转成...

    前段时间遇到一个效果处理,需要将table中超长的内容转换给….,原内容在鼠标hover时展示。目前css3提供一个属性ellipsis ,但是ellipsis对浏览器特别挑。所以用js写一个跨浏览器的ellipsis效果。

 

效果展示:


js效果,将table中多余的内容转成..._第1张图片

 

 

 核心代码:

 

/*
 * @param  tdSelector : 
 		td's selectror , if selector is null ,then all  tags will be add ellipsis's effect.
 */
function tableEllipsis(tdSelector){
	
	var td = tdSelector;
	if(!td){
		td = "td";
	}
	
	$(td).each(function(){
		
		if($(this).children().length == 0){
			//td's content
			var text = $.trim($(this).text().replace(/\s+/g,""));
		
			//add tds' title
			$(this).attr("title",text);
			
			//calcute tds' width
			var width = $(this).width(); //the developed width of  tag
			var strWidth = getStringWidth(text); //the developed width of 's content
			var ellipsisWidth = getStringWidth("..............") //the developed width of "..............", NB: string "............" must has more than three ellipsis
			if(strWidth > width){
				var offet = (strWidth-width + ellipsisWidth) / strWidth ; 
				
				text = text.substring(0 , text.length * (1-offet))+"...";
			}
			this.innerHTML = ""+text+"";
		}
	});
}


function getStringWidth(text){
	var span = $("#tempStrWidth");
	if(span.length == 0){
		span = "";
		$("body").append(span);
	}else{
		$("#tempStrWidth").html(text);
	}
	
	var result = $("#tempStrWidth").outerWidth(true);
	
	$("#tempStrWidth").html("");
	
	return parseInt(result);
}

 

 

调用方式:

 

 
 
 

你可能感兴趣的:(js效果,table,ellipsis,....)