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

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

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

?

效果展示:



?

?

?核心代码:

?

/*
 * @param  tdSelector : 
 		td's selectror , if selector is null ,then all <td> 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 <td> tag
			var strWidth = getStringWidth(text); //the developed width of <td>'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 = "<nobar>"+text+"</nobar>";
		}
	});
}


function getStringWidth(text){
	var span = $("#tempStrWidth");
	if(span.length == 0){
		span = "<span id='tempStrWidth' style='z-index:-999;visibility:hidden;'>"+text+"</span>";
		$("body").append(span);
	}else{
		$("#tempStrWidth").html(text);
	}
	
	var result = $("#tempStrWidth").outerWidth(true);
	
	$("#tempStrWidth").html("");
	
	return parseInt(result);
}

?

?

调用方式:

?

<script type="text/javascript">
		$(document).ready(function() {
			var tdSelector = "table[id='ellipsis'] td";
			
			//add ellipsis to <td> tags
			tableEllipsis(tdSelector);
		});
</script>

?
?
?