纯 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];
if (encodeURI(a).length > 6) { str_length += chineseWidth; } else if (encodeURI(a) === encodeURI(" ")) { str_length += spaceWidth; } else { str_length += englishWidth; }
if (str_length > totalLen && !cutStr) { cutStr = `${str.slice(0, i - 2)}...`; }
if (str_length > line * containerWidth) { return cutStr; } } console.log(str_length);
return ""; });
|
缺点:
- 在一些字体大小是动态单位时不适用,如小程序的 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; }
|
当 showbox 的高度比 content 高度小时,判定为溢出,toggle 为 true
将 content 内容设为 overflowHidden