不定高多行溢出文本省略

来源:互联网 发布:js ui隐藏不安全 编辑:程序博客网 时间:2024/06/05 04:31

大家应该都知道用text-overflow:ellipsis属性来实现单行文本的溢出显示省略号(…)。当然部分浏览器还需要加宽度width属性。

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

WebKit浏览器或移动端的页面

在WebKit浏览器或移动端(绝大部分是WebKit内核的浏览器)的页面实现比较简单,可以直接使用WebKit的CSS扩展属性(WebKit是私有属性)-webkit-line-clamp ;注意:这是一个 不规范的属性(unsupported WebKit property),它没有出现在 CSS 规范草案中。

常见结合属性:
display: -webkit-box; 必须结合的属性 ,将对象作为弹性伸缩盒子模型显示 。
-webkit-box-orient 必须结合的属性 ,设置或检索伸缩盒对象的子元素的排列方式 。
text-overflow: ellipsis;,可以用来多行文本的情况下,用省略号“…”隐藏超出范围的文本 。

overflow : hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-line-clamp: 2;-webkit-box-orient: vertical;

跨浏览器兼容的方案

比较靠谱简单的做法就是设置相对定位的容器高度,用包含省略号(…)的元素模拟实现;
有个缺点:内容不够3行,末尾也会加省略号

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;}

JavaScript 方案

用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.dotdotdot或http://dotdotdot.frebsite.nl/

0 0
原创粉丝点击