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
參數調整為所需的字元數。