单行省略就不用说了,用css实现很是简单,兼容性还很是好。可是多行省略一直都是前端的痛点,在css3以前,能够用js去算两行能放多少个字,把多余的字用 。。。 代替,且不说好很差,万一哪天PM说要改为3行,UI说这个字体改大一点,又得去算一遍,可谓是苦不堪言。css
好在有css3,css3提供了实现完美的多行省略方法,本文已scss为例前端
@mixin ellipsis($lineCount: 2) { text-overflow: -o-ellipsis-lastline; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: $lineCount; line-clamp: $lineCount; -webkit-box-orient: vertical; }
咋们想要几行省略的时候直接调用这个方法,传入行数,就能完美实现,不须要去计算。css3
可是,可是,,兼容性一直是个问题啊,能够看出,必需要加上前缀才能生效,就不说IE了,就连低端的Android手机都不兼容,真是头疼。。。web
难道就没有别的办法了吗?sass
no!!css 是博大精深的,尤为是预编译css工具更强大,例以下面就是 scss的写法,其余less,sass相似less
@mixin multiLineEllipsis($lineHeight: 1.2em, $lineCount: 2, $bgColor: white) { overflow: hidden; position: relative; line-height: $lineHeight; max-height: $lineHeight * $lineCount; text-align: justify; &:before { content: '...'; width: 1em; position: absolute; right: 0; bottom: 0; background-color: $bgColor; } &:after { content: ''; position: absolute; right: 0; width: 1em; height: 1em; margin-top: 0.5em; background: $bgColor; } }
简单解释一下,工具
lineHeight 就是一行的高度,便于计算高度
lineCount 须要几行省略
bgColor 背景颜色
就是巧妙的运用了高度的原理,在没有达到高度的时候显示的是 after,当超出高度的时候显示before 。字体