跳到主要内容

文本溢出省略

单行:

width: 300px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;

多行:

display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; // 行数 overflow: hidden; text-overflow: ellipsis;

多行,文本一定溢出情况:

div{ width: 300px; position: relative; line-height: 1.4em; height: 4.2em; overflow: hidden; } div::after{ content: "..."; position: absolute; right: 0; bottom: 0; }

兼容:

p { position: relative; line-height: 20px; max-height: 40px; overflow: hidden; } p::after{ content: "..."; position: absolute; bottom: 0; right: 0; padding-left: 40px; background: -webkit-linear-gradient(left, transparent, #fff 55%); background: -o-linear-gradient(right, transparent, #fff 55%); background: -moz-linear-gradient(right, transparent, #fff 55%); background: linear-gradient(to right, transparent, #fff 55%); }

JS 实现

<p>这是一段测试文字,this is some test text,测试文字,测试文字测 </p>
const p = document.querySelector('p')
let words = p.innerHTML.split(/(?<=[\u4e00-\u9fa5])|(?<=\w*?\b)/g)
while (p.scrollHeight > p.clientHeight) {
words.pop()
p.innerHTML = words.join('') + '...'
}

参考