HTML 结构:

  1. <div class="ellipsis">
  2. 测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试
  3. </div>

单行文本

CSS 代码:

.ellipsis {
  width: 100px;
  height: 1.5em;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

image.png

多行文本(webkit私有属性)

CSS 代码:

.ellipsis {
  width: 100px;
  height: 3em;
  line-height: 1.5em;
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  text-overflow: ellipsis;
  -webkit-line-clamp: 2;
}

image.png

多行文本(伪类元素)

CSS 代码:

.ellipsis {
  position: relative;
  width: 100px;
  max-height: 3em;
  line-height: 1.5em;
  overflow: hidden;
}
.ellipsis::before {
  content: '...';
  position: absolute;
  z-index: 1;
  bottom: 0;
  right: 0;
  width: 1.5em;
  padding-left: 2px;
  box-sizing: border-box;
  background-color: white;
}
.ellipsis::after {
  content: '';
  display: inline-block;
  position: absolute;
  z-index: 2;
  width: 100%;
  height: 100%;
  background-color: white;
}

image.png

PS:最后一个文字可能会被遮盖住部分

多行文本(JS计算)

const text = '这是一段很长的文本';
const totalTextLen = text.length;
const formatStr = (lineNum = 2) => {
  const ele = document.getElementsByClassName('demo')[0];
  const eleInfo = window.getComputedStyle(ele)
  const {
    width: baseWidth,
    fontSize: baseFontSize
  } = eleInfo
  const lineWidth = +baseWidth.slice(0, -2);

  // 所计算的strNum为元素内部一行可容纳的字数(不区分中英文)
  const strNum = Math.floor(lineWidth / +baseFontSize.slice(0, -2));

  let content = '';

  // 多行可容纳总字数
  const totalStrNum = Math.floor(strNum * lineNum);

  const lastIndex = totalStrNum - totalTextLen;

  if (totalTextLen > totalStrNum) {
    content = text.slice(0, lastIndex - 3).concat('...');
  } else {
    content = text;
  }
  ele.innerHTML = content;
}

image.png

参考: