一、css方法
1、单行文本p{
width:100px;
overflow: hidden; /*超出部分隐藏*/
white-space: nowrap; /*禁止换行*/
text-overflow: ellipsis; /*省略号*/
}
2、多行文本
这个属性只合适WebKit浏览器或移动端(绝大部分是WebKit内核的)浏览器
p{
width:100px;
height:40px;/*需要展示行高度*/
display: -webkit-box; /* 必须结合的属性 ,将对象作为弹性伸缩盒子模型显示 。*/
-webkit-box-orient: vertical; /* 必须结合的属性 ,设置或检索伸缩盒对象的子元素的排列方式 。*/
text-overflow: ellipsis; /* 可以用来多行文本的情况下,用省略号“…”隐藏超出范围的文本 。*/
-webkit-line-clamp: 2;
overflow : hidden;
}
跨浏览器(浏览器需支持伪元素)
p {
position: relative;
line-height: 1.4em;
/* 3 times the line-height to show 3 lines */
height: 4.2em;
overflow: hidden;
}
p::after {
content: "\02026";/*...*/
font-weight: bold;
position: absolute;
bottom: 0;
right: 0;
padding: 0 20px 1px 45px;
background:-webkit-linear-gradient(left,transparent,#fff 55%);
background:-o-linear-gradient(right,transparent,#fff 55%);
background:-moz-linear-gradient(right,transparent,#fff 55%);
background:linear-gradient(to right,transparent,#fff 55%);
}
二、js方法
function substrLength(elementId,length){ //elementId:元素id,length:需保留字符串长度
var text=document.getElementById(elementId);
var result = "";
if(text.innerText.length > length){
result = text.innerText.substr(0,length)+"...";
}else{
result = text.innerText;
}
text.innerText=result;
}
substrLength('ID','length');