js和css实现内容超过边框,就自动省略,自动添加title

时间:2023-03-08 20:17:43

在项目汇总,我们有这样的需求,如果内容多了,就自动省略,自动添加title

这个需要判断判断俩个值,一个是width(),一个是scrollWidth,

在div中,如果内容没有超过边框,这俩个值是一样的,就是css设置的宽度;如果内容超过边框了,scrollWidth的值会大于width,所以我们可以通过判断scrollWidth和width的值

来知道内容是否超过边框

例:

 <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1,minimum-scale=1,maximum-sacle=1,user-scalable=no">
<script type="text/javascript" src="../jquery-3.1.1.js"></script>
<style>
.test1{
width: 200px;
height: 20px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>
</head>
<body>
<div>
<div class="test1">阿尔瓦尔</div>
<div class="test1">阿尔瓦尔方式顶顶顶顶顶顶顶顶顶顶顶顶顶顶多多多多多多多多多多多多多多多多多多多多</div>
</div>
<script>
$(function () {
console.log($(".test1").eq().width())
console.log($(".test1").eq()[].scrollWidth)
for(var i = ;i<$(".test1").length;i++){
if($(".test1").eq(i).width() < $(".test1").eq(i)[].scrollWidth){
$(".test1").eq(i).attr("title",$(".test1").eq(i).text())
}
}
})
</script>
</body>
</html>

在table中,就不能这样判断了,就算内容没有超过边框,scrollWidth也会大于width,所以我们只用scrollWidth就行,先通过计算获取内容少时scrollWidth的值,然后同判断

如果当前的scrollWidth大于之前计算的值,就说明内容超过边框了

例:

 <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1,minimum-scale=1,maximum-sacle=1,user-scalable=no">
<script type="text/javascript" src="../jquery-3.1.1.js"></script>
<style>
table{
width: 1080px;
table-layout: fixed;
border-collapse: collapse;
margin: auto;
}
thead{
width: auto;
font-size: 14px;
text-align: center;
background-color: #;
}
thead tr,thead th{
border: 1px solid #dddddd;
border-left: none !important;
color: #ffffff;
height: 50px;
font-size: 14px;
}
thead tr img,tbody td img{
width: 14px;
height: 14px;
cursor: pointer;
} tbody{
width: auto;
min-width: 1070px;
font-size: 14px;
text-align: center;
border-bottom: 1px solid #dddddd;
background-color: #ffffff;
}
tbody tr,tbody td{
border-left: 1px solid #dddddd;
border-right: 1px solid #dddddd;
height: 67px;
color: #;
}
tbody td{
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>
</head>
<body>
<table>
<tbody>
<tr>
<td class="test2">我是</td>
<td class="test1" width="">我是1反倒</td>
<td>我是2</td>
</tr>
<tr>
<td>我是</td>
<td class="test1" width="">我是1反倒是所所所所所所所所所所所所所所所所所所所所我是1反倒是所所所所所所所所所所所所所所所所所所所所我是1反倒是所所所所所所所所所所所所所所所所所所所所</td>
<td>我是2</td>
</tr>
<tr>
<td>我是</td>
<td class="test1" width="">我是1反倒是所所所所所所所所所所所所所所所所所所所所我是1反倒是所所所所所所所所所所所所所所所所所所所所我是1反倒是所所所所所所所所所所所所所所所所所所所所</td>
<td>我是2</td>
</tr>
</tbody>
</table>
<script>
$(function () {
// 352是最开始算出来的,当内容很少时,scrollWidth值是352
for(var i = ;i<$(".test1").length;i++){
if($(".test1").eq(i)[].scrollWidth > ){
$(".test1").eq(i).attr("title",$(".test1").eq(i).text())
}
}
})
</script>
</body>
</html>