说说单行和多行文本溢出的实现方式
# 是什么
文本溢出: 元素内容宽度过长,不能完全显示, 把不能显示的文本用省略号显示...
# 实现方式
- 单行文本
- 多行文本
# 单行文本
p{
width:400px;
overflow:hidden;
white-space:nowrap;
text-overflow: ellipsis;
}
- text-overflow只有在设置了overflow:hidden和white-space:nowrap才能够生效的
- clip 超出裁切
- ellipsis 超出显示省略号
# 多行文本
- 基于高度溢出
- 基于行数溢出
# 基于高度溢出
- 在已知高度情况下
- 兼容性好
- 响应式
<style>
.p1{
position: relative;
width: 200px;
height: 40px;
line-height: 20px;
overflow: hidden;
}
.p1::after{
content: '...';
position: absolute;
right: 0;
bottom: 0;
padding: 0 20px 0 10px;
word-break: break-all;
background-color: #FFF;
}
</style>
<p class="p1">我是文本我是文本我是文本我是文本我是文本我是文本我是文本我是文本我是文本我是文本我是文本我是文本我是文本</p>
<p class="p1">hello world,hello world,hello world,hello world,hello world,hello world,</p>
- 未知高度(动态js设置)
<style>
.p3{
position: relative;
width: 200px;
line-height: 20px;
overflow: hidden;
}
.p3-after::after{
content: '...';
position: absolute;
right: 0;
bottom: 0;
padding-left: 40px;
background: -webkit-linear-gradient(left, transparent, #fff 55%);
word-break: break-all;
}
</style>
<p class="p3">
我是文本我是文本我是文本我是文本我是文本我是文本我是文本我是文本我是文本我是文本我是文本我是文本我是文本
</p>
<script>
const p3 = $('.p3')
const lh = parseInt(p3.css('line-height'))
const p3Height = p3.height()
if(p3Height/lh > 1){
p3.addClass('p3-after')
p3.height('60')
} else {
p3.removeClass('p3-after')
}
</script>
# 基于行数溢出
- webkit 移动端适用
<style>
.p2{
width: 200px;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
white-space:break-all;
}
</style>
<p class="p2">我是文本我是文本我是文本我是文本我是文本我是文本我是文本我是文本我是文本我是文本我是文本我是文本我是文本</p>
<p class="p2">hello world,hello world,hello world,hello world,hello world,hello world,</p>
上次更新: 2021/12/19, 18:05:42