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>

 
 
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值