在日常开发中,如果一段文本的数量过长,为了提高用户的使用体验,我们把溢出的文本显示成省略号的方式
对于文本的溢出,我们可以分为两种形式:单行文本的溢出,多行文本的溢出
有些时候,我们还需要更改省略号的样式,比如将省略号更改为我们自定义的内容,或者图标。下面记录一下实现过程。
1.单行文本溢出
效果:
代码:
<div class="demo">
我真帅我真帅我真帅我真帅 我真帅我真帅我真帅我真帅
</div>
.demo{
/* 限制容器宽度 */
width: 100px;
/* 文字强制不换行 */
white-space: nowrap;
/* 文字溢出换省略号 */
text-overflow: ellipsis;
/* 溢出文字隐藏 */
overflow: hidden;
}
2.多行文本溢出
方法一:需要使用webkit的css属性扩展,兼容浏览器范围是pc端webkit内核的浏览器,由于移动端大多数是使用的webkit,对于移动端友好。长英文或数字,需要添加 word-wrap: break-word。
效果:
代码:
<div>
<p class="p"> 我真帅我真帅我真帅我真帅 我真帅我真帅我真帅我真帅</p>
</div>
.p {
height: 60px;
line-height: 30px;
width: 80px;
overflow : hidden;
text-overflow: ellipsis;
display: -webkit-box; /*设置弹性伸缩盒子*/
-webkit-line-clamp: 2; /*省略号在第几行*/
-webkit-box-orient: vertical; /*对齐方式*/
}
方法二:伪元素加定位
效果:
代码:
<div class="demo">
我真帅我真帅我真帅我真帅 我真帅我真帅我真帅我真帅
</div>
.demo {
position: relative;
line-height: 20px;
height: 40px;
width: 80px;
overflow: hidden;
}
/* 设置样式,通过定位调整位置 */
.demo::after {
content: '...';
position: absolute;
bottom: 0;
right: 0;
background-color:white ;
}
3.自定义省略图标
伪元素加定位的优点是可以设置自定义省略样式,比如把省略号换为图标
效果:
代码 :
<div class="demo">
我真帅我真帅我真帅我真帅 我真帅我真帅我真帅我真帅
</div>
.demo {
position: relative;
height: 50px;
line-height: 25px;
overflow: hidden;
width: 100px;
}
.demo::after {
width: 20px;
height: 20px;
content: "";
/* 使用背景图片,否则无法调整图片大小 */
background-image: url("../assets/2.png");
background-size: contain;
position: absolute;
bottom: 0px;
right: 0px;
}
4.动态添加省略号
容器高度之内不添加,超过容器边界后添加省略号
使用overflow:auto配合js
效果:
代码 :
<div id="view">
</div>
#view{
width:100px;
height:50px;
overflow:auto;/*溢出显示滚动条*/
}
const el:any = document.getElementById('view');
const n = el.offsetHeight;//窗口设定高度
// el.scrollHeight为滚动高度
for(let i=0; i<s.length; i++) {
el.innerHTML = s.substr(0,i);
// 一开始 el.offsetHeight与el.scrollHeight高度相等
// 只有到达触发滚动的时候,el.scrollHeight会比 el.offsetHeight大,此时需要省略号
if(n < el.scrollHeight) {
el.style.overflow = 'hidden';
el.innerHTML = s.substr(0, i-3) + '...';
break;
}
}