---
title: "js效果,将table中多余的内容转成..."
author: "mark_5528"
date: "2013-09-26T15:48:16Z"
tags: ["table"]
categories: ["Web前端"]
slug: "js-table"
draft: false
lastmod: "2013-09-26T15:48:13Z"
id: 1947667
url: "https://mark-5528.iteye.com/blog/1947667"
---

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

 

效果展示：

![](http://dl2.iteye.com/upload/attachment/0089/6943/49551492-4018-3952-8555-dd31d26f89f0.png)

 

 

 核心代码：

 

```
/*
 * @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>
```