限制文本行数

1行:

white-space:nowrap;overflow:hidden;text-overflow:ellipsis;

  

ps*:一定要指定容器的宽度,不然的话是没有用的。

多行:

方法一:只支持-webkit内核,不支持火狐

<p style="
overflow : hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
">

方法二: 不管怎样,省略号都会出现,建议配合js,只有超出高度时,才显示::after

p {
    position:relative;
    line-height:1.4em;
    /* 3 times the line-height to show 3 lines */
    height:4.2em;
    overflow:hidden;
}
p::after {
    content:"...";
    font-weight:bold;
    position:absolute;
    bottom:0;
    right:0;
    padding:0 20px 1px 45px;
    background:url(http://css88.b0.upaiyun.com/css88/2014/09/ellipsis_bg.png) repeat-y;
}

  

这里注意几点:

  1. height高度真好是line-height的3倍;
  2. 结束的省略好用了半透明的png做了减淡的效果,或者设置背景颜色;
  3. IE6-7不显示content内容,所以要兼容IE6-7可以是在内容中加入一个标签,比如用<span class="line-clamp">...</span>去模拟;
  4. 要支持IE8,需要将::after替换成:after

js方案:

1.Clamp.js

下载及文档地址:https://github.com/josephschmitt/Clamp.js
使用也非常简单:

var module = document.getElementById("clamp-this-module");
$clamp(module, {clamp: 3});

  

2.jQuery插件-jQuery.dotdotdot

$(document).ready(function() {
	$("#wrapper").dotdotdot({
		//	configuration goes here
	});
});

下载及详细文档地址:https://github.com/BeSite/jQuery.dotdotdothttp://dotdotdot.frebsite.nl/

3.js

除了各个浏览器私有的属性,有没有跨浏览器的解决方法呢?当然是通过js实现啦!(通过从后向前逐个删除末尾字符,直至元素的高度小于父元素高度)

$(".figcaption").each(function(i){
    var divH = $(this).height();
    var $p = $("p", $(this)).eq(0);  //文字在这个p内
    while ($p.outerHeight() > divH) {
        $p.text($p.text().replace(/(s)*([a-zA-Z0-9]+|W)(...)?$/, "..."));
    };
});

  

原文地址:https://www.cnblogs.com/ghfjj/p/6635954.html