如何使用文字溢出防止斷字
P粉464208937
P粉464208937 2023-09-03 15:00:49
0
1
524
<p>我正在嘗試為某些標題設定最大行數,但問題是有時一行會以斷詞結尾。我需要的是,如果一個單字必須被打破,它應該被完全隱藏,並且省略號放在前一個單字之後。 </p> <p>此程式碼顯示了問題:</p> <p> <pre class="brush:css;toolbar:false;">#head { width:300px; font-size: 20px; display: -webkit-box !important; color: #000000 !important; text-overflow: ellipsis !important; -webkit-line-clamp: 4 !important; -webkit-box-orient: vertical !important; overflow: hidden !important; }</pre> <pre class="brush:html;toolbar:false;"><!DOCTYPE html> <html> <div id="head"> 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 scramble a scramble scake a scramley of type and scramble a scend </div> </html></pre> </p> <p>「曾經」這個字中間斷了,我能以某種方式阻止這種情況發生嗎? </p>
P粉464208937
P粉464208937

全部回覆(1)
P粉231112437

要達到完全隱藏斷詞並將省略號放在前一個字後面的效果,您可以使用 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 參數調整為所需的字元數。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!