在前端开发以及小程序开发中,单行,多行文本溢出隐藏经常用到。接下来我就把我知道的几种情况整理出来以供大家参考。
微信小程序
多行text文本溢出隐藏
display: -webkit-box;
word-break: break-all;
-webkit-box-orient: vertical;
-webkit-line-clamp:3; // 你想要的行数
overflow: hidden;
text-overflow:ellipsis;
单行text文本隐藏
display: block;
overflow: hidden;
white-space: nowrap;
text-overflow:ellipsis;
HTML
单行文本隐藏
display: block;
overflow: hidden;
white-space: nowrap;
text-overflow:ellipsis;
多行溢出隐藏
这种写法存在浏览器兼容性
width: 150px;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
overflow: hidden;
跨浏览器兼容性可以用绝对定位和相对定位实现
div {
position:relative;
line-height:100px;
height:300px;
overflow:hidden;
}
div::after {
content:"...";
position:absolute;
bottom:0;
right:0;
padding:20px;
background:url() repeat-y;
}
这里要注意两点:
- 你想要设置几行隐藏,就把height设置为行高的几倍。
- 结束的省略号尽量用半透明的png做减淡的效果,或者设置背景颜色
jQuery实现,这个主要通过显示的字数实现
div{
width: 200px;
height: 100px;
margin: 0 auto;
line-height: 20px;
}
$(function(){
let content_arr=[];
$('div').each(function(){
content_arr.push($(this).text());//内容放进数组
})
for(var i=0;i<content_arr.length;i++){//遍历循环数组
if(content_arr[i].length>=100){
content=content_arr[i].substr(0,100)+'...';
$("div").eq(i).text(content);
}else{
content=content_arr[i];
$("div").eq(i).text(content);
}
}
})
注意:
数字100就是控制溢出隐藏的关键,可以根据你的需求自定义。
欢迎纠错补充!