单行
.overflow {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
}
多行
.overflow_2 {
display: -webkit-box !important;-webkit-box-orient: vertical;
text-overflow: ellipsis;
overflow: hidden;
display: -moz-box !important;
word-break: break-all;
-webkit-line-clamp: 2;
}
js 原理是:计算字节的方法,1个英文一个位置一个中文占两个位置,给一个总位置,处理获取的字符串再控制显示
function ellipsis(totalWords,ele) {
var count = 0,
text = $(ele).html(),//考虑换行导致的空格可以使用(此方法不兼容IE8):text = $(ele).html().trim()
startUnicode = parseInt("0x4e00", 16),//最小中文Unicode
endUnicode = parseInt("0x9fa5", 16);//最大中文Unicode
for (var i = 0,len=text.length; i <len; ++i) {
var e = text[i];
if (count <= totalWords) {//如果没达到最大长度就累加
if (e.charCodeAt(0) >= startUnicode && e.charCodeAt(0)<= endUnicode) {
count += 2;
} else {
count++;
}
} else {//否则就显示处理并且return
text = text.substring(0, i - 3);
$(ele).html(text + "...");
return;
}
}
}
ellipsis(需要显示的单词量,元素)