如何使用文本溢出防止断字
P粉464208937
P粉464208937 2023-09-03 15:00:49
0
1
523
<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 scrambled it to make a </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学习者快速成长!