css3 javascript 单行和多行文本溢出截断多种方案

4,741 阅读2分钟

写在最前面

  • 在我们日常开发中的时候经常会遇到一种业务场景,需要截断一些文字的显示。可能是一行或者两行,或者根据字数限制或者用户的显示屏幕大小来展示对应的文字。

css 篇

一:单行文本溢出处理

代码

.text-ellipsis-single{
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

分析

  • 兼容性好,但是只支持一行,可以简单满足截断的文本的要求

二:多行文本截断

代码

  • 多行文本注意设置 line-height
.text-ellipsis-multiple{
    -webkit-line-clamp: 2;// webkit 内核浏览器支持的行数
    display: -webkit-box;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;// clip|ellipsis|string 截断|省略号|自定义字符串
}
  • 如果你使用 scss 的话我们可以自定义行数使用,设置 line-hight 和 max-height 最大显示的行高和高度再限制一下显示的问题
@mixin multiline-ellipsis($line: 2, $line-height: 1.6em) {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: $line;
  -webkit-box-orient: vertical;
  line-height: $line-height;
  max-height: $line-height * $line;
}

分析

  • 兼容性问题,移动端兼容性尚可
  • 这里使用到了 -webkit- 等内核的方法,看看各个浏览器的兼容性,移动端多用于-webkit,

三:兼容性较好的 css3 方案

代码

@minxin text-ellipsis-multiple-compatibility($line: 3, $line-height: 1.6em) {
    position:relative;
    line-height:$line-height;
    height:$line-height * $line;
    overflow:hidden;
}

.text-ellipsis-multiple-compatibility{
    @inlcude text-ellipsis-multiple-compatibility(3);
    
    &::after{
        content:"...";
        font-weight:bold;
        position:absolute;
        bottom:0;
        right:0;
        padding:0 20px 1px 45px;
       }
}

分析

  • 用伪元素模拟省略号,兼容性较好,但是展示有部分问题,可能需要结合部分 javascript 进行微调。

  • 如果涉及到英文,需要截断单词可以优化一下。

.perf{
    word-break: break-all;
    word-wrap:break-word
}

javascript 篇

一:限制最大字数的截断,单行文本简单实现

  • 代码
// 字数限制30字,超出省略号代替
function Truancate(textHolder, limit = 30) {
  let txt = textHolder.innerHTML;
  if (txt.length > limit) {
    let newText = txt.substr(0, limit) + ' ...';
    textHolder.innerHTML = newText;
  }
}  

二:计算行数截断多行文本

javascript 方法

  • 我们也可以直接计算
function ellipsizeTextElement($element) {
    var nodeList = document.querySelectorAll($element);
    var elements = Array.prototype.slice.call(nodeList, 0);
    elements.forEach(function(element) {
      var wordArray = element.innerHTML.split(' ');
      while (element.scrollHeight > element.offsetHeight) {
        wordArray.pop();
        element.innerHTML = wordArray.join(' ') + '...';
      }
    });
  }

分析

  • 兼容性好,但是相对来说比较麻烦

额外浮动 css 方案

body {
  background-color: #fff;
}

.parent {
  line-height: 20px;
  max-height: 60px;
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    width: 20px;
    height: 60px;
    float: left;
  }
  
  &::after {
    content: '...';
    left: 100%;
    width: 20px;
    height: 20px;
    background-color: #fff;
    float: right;
    position: relative;
    box-shadow: -4px 0 2px #fff;
    transform: translate(-100%, -100%);
  }
}

.content {
  width: 100%;
  margin-left: -20px;
  float: right;
}

分析

  • 伪元素,浮动布局,关健的 transform: translate(-100%, -100%); 遮挡末尾的文字
  • 兼容性很好,调参比较麻烦,适应简单的需求

使用第三方库

参考