Heim > Fragen und Antworten > Hauptteil
P粉2311124372023-09-04 10:19:09
要达到完全隐藏断词并将省略号放在前一个词后面的效果,您可以使用 JavaScript 来操作文本内容。以下是如何修改代码以实现此目的的示例:
function truncateText(element, maxLength) { const text = element.innerText; if (text.length <= maxLength) return; const truncatedText = text.slice(0, maxLength); const lastSpaceIndex = truncatedText.lastIndexOf(' '); element.innerText = truncatedText.slice(0, lastSpaceIndex) + '...'; } const headlineElement = document.getElementById('headline'); truncateText(headlineElement, 100);
#head { width: 300px; font-size: 20px; display: -webkit-box !important; color: #000000 !important; -webkit-line-clamp: 4 !important; -webkit-box-orient: vertical !important; overflow: hidden !important; }
<div id="head"> <span id="headline"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a </span> </div>
在此代码中,JavaScript 函数 truncateText
用于在文本内容超过指定的最大长度时截断文本内容。该函数查找最大长度内的最后一个空格字符,并用省略号替换剩余的文本。
在添加省略号之前,您可以将 maxLength
参数调整为所需的字符数。