只需要两步搞定:
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>
来源:CSDN
作者:x_apricot
链接:https://blog.csdn.net/huangxinglian/article/details/87875049