表格内容超出单元格时以省略号显示,鼠标悬停显示完整内容

家住魔仙堡 提交于 2019-11-27 11:00:17

只需要两步搞定:

1.第一步,写样式:设置单元格的宽度,超出部分用...代替

#tableEg td {  
	max-width:180px;  
	overflow:hidden;  
	white-space:nowrap;  
	text-overflow:ellipsis;  
	-o-text-overflow:ellipsis;  
	-icab-text-overflow: ellipsis;  
	-khtml-text-overflow: ellipsis;  
	-moz-text-overflow: ellipsis;  
	-webkit-text-overflow: ellipsis;  
}

2.第二步,写js代码,超出部分用鼠标悬停时,tooltip显示完整内容

$(document).on('mouseenter', "#tableEg td", function () {
        
    if (this.offsetWidth < this.scrollWidth) {
        $(this).attr('data-toggle', 'tooltip').attr('title', $(this).text());
    }

});
$(document).on('mouseleave', '#tableEg td', function () {

    $(this).attr('data-toggle', '');

});

完整代码:

<!DOCTYPE html>
<html>
<head>
	<title>表格内容超出容器以省略号显示</title>
	<style>
		/*第一步,写样式:设置单元格的宽度,超出部分用...代替*/
		#tableEg { width:400px; }
		#tableEg td {  
		  max-width:180px;  
		  overflow:hidden;  
		  white-space:nowrap;  
		  text-overflow:ellipsis;  
		  -o-text-overflow:ellipsis;  
		  -icab-text-overflow: ellipsis;  
		  -khtml-text-overflow: ellipsis;  
		  -moz-text-overflow: ellipsis;  
		  -webkit-text-overflow: ellipsis;  
		}
	</style>
</head>
<body>
	<div id="tableParent">
		<table id="tableEg" class="table" border="1" cellspacing="0">
			<thead>
				<tr>
					<th>单价</th>
					<th>数量</th>
					<th>描述</th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<td>10</td>
					<td>50</td>
					<td>向响应式对象中添加一个属性,并确保这个新属性同样是响应式的,且触发视图更新。它必须用于向响应式对象上添加新属性,因为 Vue 无法探测普通的新增属性 </td>
				</tr>
				<tr>
					<td>10</td>
					<td>50</td>
					<td>向响应式对象中添加一个属性,并确保这个新属性同样是响应式的,且触发视图更新。它必须用于向响应式对象上添加新属性,因为 Vue 无法探测普通的新增属性 </td>
				</tr>
				<tr>
					<td>10</td>
					<td>50</td>
					<td>向响应式对象中添加一个属性,并确保这个新属性同样是响应式的,且触发视图更新。它必须用于向响应式对象上添加新属性,因为 Vue 无法探测普通的新增属性 </td>
				</tr>
			</tbody>
		</table>
	</div>
	<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
	<script type="text/javascript">
		/*第二步,写js代码,超出部分用鼠标悬停时,tooltip显示完整内容*/
		$(document).on('mouseenter', "#tableEg td", function () {
        
	        if (this.offsetWidth < this.scrollWidth) {
	            $(this).attr('data-toggle', 'tooltip').attr('title', $(this).text());
	        }
	    });
	    //鼠标离开时,tooltip消失
	    $(document).on('mouseleave', '#tableEg td', function () {
	        $(this).attr('data-toggle', '');
	    });
	</script>
</body>
</html>

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!