纯 JS

当规定行数展示文本,多出来进行省略显示,并加上展示符号

const cutStr = computed(() => {
const str = intro.value;
const fontSize = 16;
const line = 2;
const containerWidth = 320;
const chineseWidth = 1 * fontSize; // 中文字符宽度
const englishWidth = 0.55 * fontSize; // 英文字符宽度
const spaceWidth = 0.27 * fontSize; // 空格宽度
const totalLen = line * containerWidth - 3 * chineseWidth;

let str_length = 0;
let cutStr = "";
for (let i = 0, len = str.length; i < len; i++) {
const a = str[i];

// 中文字符的长度经编码之后大于6
if (encodeURI(a).length > 6) {
str_length += chineseWidth;
} else if (encodeURI(a) === encodeURI(" ")) {
str_length += spaceWidth;
} else {
str_length += englishWidth;
}

// 达到目标长度,即为字符串加上省略号并返回,-3是为了空3个中文出来展示 展开 文案
if (str_length > totalLen && !cutStr) {
cutStr = `${str.slice(0, i - 2)}...`;
}

if (str_length > line * containerWidth) {
return cutStr;
}
}
console.log(str_length);

return "";
});

缺点:

  1. 在一些字体大小是动态单位时不适用,如小程序的 rpx

小程序 JS+CSS

结构

<div class="show-box">
<div class="content"></div>
<div v-if="toggle" class="expand">...显示更多</div>
</div>
.show-box {
max-height: 100rpx;
overflow: hidden;
position: relative;
}
.expand {
position: absolute;
right: 0;
bottom: 0;
}
  1. 当 showbox 的高度比 content 高度小时,判定为溢出,toggle 为 true

  2. 将 content 内容设为 overflowHidden