How to prevent hyphenation using text overflow
P粉464208937
P粉464208937 2023-09-03 15:00:49
0
1
520
<p>I'm trying to set a maximum number of lines for some titles, but the problem is that sometimes a line ends with a hyphen. What I need is that if a word has to be broken, it should be completely hidden and the ellipses placed after the previous word. </p> <p>This code shows the problem: </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>There is a break in the word "ever", can I somehow prevent this from happening? </p>
P粉464208937
P粉464208937

reply all(1)
P粉231112437

To achieve the effect of completely hiding the word break and placing the ellipsis after the previous word, you can use JavaScript to manipulate the text content. Here is an example of how to modify the code to achieve this:

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>

In this code, the JavaScript function truncateText is used to truncate the text content when it exceeds the specified maximum length. This function finds the last space character within the maximum length and replaces the remaining text with ellipses.

You can adjust the maxLength parameter to the desired number of characters before adding the ellipsis.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!