本文参考链接:http://www.cnblogs.com/penghuwan/p/6682303.html#_label1_0
- css实现单行省略
<p style='overflow: hidden;text-overflow:ellipsis;white-space: nowrap;width:400px;border:1px solid red;'>
这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本
</p>
2. css实现多行省略(不兼容火狐浏览器)
<div style = 'width:400px;height:70px;border:1px solid red;'>
<p style='display:-webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 2;overflow:hidden;'>
这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本
</p>
</div>
3. css实现多行省略(定位的方法)
<div style='position:relative;width:400px;height:45px;border:1px solid red;overflow:hidden;'>
<div id="view">这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本</div>
<p id="icon" style='position:absolute;right:0;bottom:6px;margin:0;background:white;'>...</p>
</div>
附上一段,如果文本不足两行是,省略号不显示的js代码,这里用的是内容高度判断。
<script>
var el = document.getElementById('view');
var n = el.offsetHeight;
if(n > 45){
document.getElementById("icon").style.display="block";
}else{
document.getElementById("icon").style.display="none";
}
</script>
- css实现多行省略(伪元素)
<style>
.view:after {
content: '…';
text-indent: 0;
position: absolute;
bottom: 0;
right: 0;
background: #fff;
padding-left: 3px;
}
</style>
<div style='position:relative;width:400px;height:45px;border:1px solid red;overflow:hidden;'>
<div class="view">这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本这是一些文本</div>
</div>
- js实现多行省略:方法一
<div id='view' style='border:1px solid red;width:200px;height:70px;overflow:auto'></div>
<script>
var s = '这是一个文本这是一个文本这是一个文本这是一个文本这是一个文本这是一个文本这是一个文本这是一个文本'
var el = document.getElementById('view');
var n = el.offsetHeight;
for(i=0; i<s.length; i++) {
el.innerHTML = s.substr(0, i);
if(n < el.scrollHeight) {
el.style.overflow = 'hidden';
el.innerHTML = s.substr(0, i-2) + '...';
break;
}
}
</script>
6. js实现多行省略:方法二
<div id='view' style='border:1px solid red;width:200px;height:45px;'>这是一个文本这是一个文本这是一个文本这是一个文本这是一个文本这是一个文本这是一个文本这是一个文本</div>
核心js。
function cutstr(str, len) {
var str_length = 0;
var str_len = 0;
str_cut = new String();
str_len = str.length;
for (var i = 0; i < str_len; i++) {
a = str.charAt(i);
str_length++;
if (escape(a).length > 4) {
str_length++;
}
str_cut = str_cut.concat(a);
if (str_length >= len) {
str_cut = str_cut.concat("...");
return str_cut;
}
}
if (str_length < len) {
return str;
}
}
调用方法
// js 写法
var str = document.getElementById("view").innerText;
cutstr(str,'45');
document.getElementById("view").innerHTML = str_cut;
// jq 写法
var str = $("#view").text();
cutstr(str,'45');
$("#view").text(str_cut);
本文通过网络摘抄,总结几种写法。具体使用哪种方法,根据具体情况判断。目前比较喜欢最后一种。第6方法,通过截取字符长度,添加省略号,可以将核心js放到项目公共js文件中,在需要进行省略的位置,进行调用;缺点,循环结果,影响页面加载速度。