Home >Web Front-end >JS Tutorial >How to Implement Ellipsis with Fixed Width and Height in Multi-Line Text?

How to Implement Ellipsis with Fixed Width and Height in Multi-Line Text?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 21:13:29957browse

How to Implement Ellipsis with Fixed Width and Height in Multi-Line Text?

Ellipsis with Fixed Width and Height in Multi-Line Text

Multi-line text overflow with ellipsis can be achieved within a fixed width and height container using JavaScript. To understand the concept, imagine a div with predefined dimensions that contains multiple lines of text.

The goal is to ensure that the text is truncated at the specified lines and appends an ellipsis to indicate continuation. Here's how it can be implemented:

  1. Overflow Property: Set the overflow property of the div to "hidden" to prevent the text from overflowing its boundaries.
  2. Line Height and Max-Height: Specify line height and max-height for the div to restrict the number of lines it can accommodate.
  3. Text Truncation: Use jQuery to repeatedly remove the last word of the text until it fits within the desired size. Here's an example:
<code class="javascript">var $p = $('#fos p');
var divh = $('#fos').height();
while ($p.outerHeight() > divh) {
    $p.text(function (index, text) {
        return text.replace(/\W*\s(\S)*$/, '...');
    });
}</code>
  1. Server-Side Truncation: Combine server-side truncation for performance and to present legible text without ellipsis when JavaScript is disabled.

This approach provides a basic solution for text overflow with ellipsis within fixed bounds. For a more comprehensive implementation, consider implementing server-side truncation or using jQuery plugins that offer enhanced functionality for text truncation.

The above is the detailed content of How to Implement Ellipsis with Fixed Width and Height in Multi-Line Text?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn