只针对google和IE浏览器分析,求他浏览器不做比较。
- 单行文字截断:google、IE均支持
.single{
width: 300px;
height: 100px;
border: 1px solid red;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
- 多行文字截断:1、只对google有用,IE不兼容;2、注意不能设置height值!!!
.multiple{
width: 300px;
/*height: 100px;*/
border: 1px solid yellow;
overflow : hidden;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
- 通过js来实现文字截断,不做说明,看源码
- 以下是上面3种方式的源码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
var wenzi=$("#jieduan").text();
var newstr=subString(wenzi,90,true);//截取90个字符显示
$("#jieduan").text(newstr);
});
/*截取文本长度。末尾补省略号...
* str:想要截断的文本
* len:截取字符串
* hasDot:是否添加省略号"..."
* 不管是汉字、数字、字母,全部转换成字符
*/
function subString(str, len, hasDot) {
var newLength = 0;
var newStr = '';
var chineseRegex = /[^\x00-\xff]/g;// 判断汉字的正则,是汉字时,用两个**代替
var singleChar = '';
var strLength = str.replace(chineseRegex, '**').length;
// 循环判断每个字符;是汉字,+2否则+1;当长度>预定值时,返回newLength长度的字符;
for (var i = 0; i < strLength; i++) {
singleChar = str.charAt(i).toString();//返回指定位置的字符
if (singleChar.match(chineseRegex) != null) {
newLength += 2;
}else {
newLength++;
}
if (newLength > len) {
break;
}
newStr += singleChar;
}
// 字符串长度>预定值,且hasDot,显示...
if (hasDot && strLength > len) {
newStr += '...';
}
return newStr;
}
</script>
<style type="text/css">
.single{
width: 300px;
height: 100px;
border: 1px solid red;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.multiple{
width: 300px;
/*height: 100px;*/
border: 1px solid yellow;
overflow : hidden;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
.original{
width: 300px;
height: 100px;
border: 1px solid blue;
}
</style>
</head>
<body>
<h3>单行文字截断:google、IE均支持</h3>
<div class="single">1980年改革开放的春风吹起不久,归国华人日渐增多。在这样的时代背景下,中国拍摄了一部反映爱国华侨心系祖国的电影《海外赤子》。</div>
<h3>多行文字截断:只对google有用,IE不兼容;注意不能设置height值!!!</h3>
<div class="multiple">1980年改革开放的春风吹起不久,归国华人日渐增多。在这样的时代背景下,中国拍摄了一部反映爱国华侨心系祖国的电影《海外赤子》。</div>
<h3>多行文字截断:使用js实现</h3>
<div class="original" id="jieduan">1980年改革开放的春风吹起不久,归国华人日渐增多。在这样的时代背景下,中国拍摄了一部反映爱国华侨心系祖国的电影《海外赤子》。1980年改革开放的春风吹起不久,归国华人日渐增多。在这样的时代背景下,中国拍摄了一部反映爱国华侨心系祖国的电影《海外赤子》</div>
</body>
</html>
Google 、IE中的效果如下: