Home  >  Article  >  Web Front-end  >  How to Fix Cross-Browser Text Overflow in Fixed-Width, Multi-Line Elements Using jQuery?

How to Fix Cross-Browser Text Overflow in Fixed-Width, Multi-Line Elements Using jQuery?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 08:48:03454browse

How to Fix Cross-Browser Text Overflow in Fixed-Width, Multi-Line Elements Using jQuery?

Fixing Cross-Browser Text Overflow in Fixed-Width, Multi-Line Elements

Consider a scenario where you have a div with a constrained width and multiple text lines. How can you ensure that overflowing text is truncated with ellipses (...)?

Multi-Line Ellipsis with jQuery

While various jQuery plugins address text overflow in some capacity, finding one specifically tailored to your requirements can be a challenge. Here's a basic approach using jQuery:

var $p = $('#fos p');
var divh = $('#fos').height();
while ($p.outerHeight() > divh) {
    $p.text(function (index, text) {
        return text.replace(/\W*\s(\S)*$/, '...');
    });
}

This script iteratively removes the last word from the text until the height matches the div. Even with JavaScript disabled, the truncated text remains visually correct.

Server-Side Optimization

Combining this approach with server-side truncation can enhance performance by leaving a minimal overhead.

Note: This solution is a starting point and may require further refinement based on your specific requirements.

The above is the detailed content of How to Fix Cross-Browser Text Overflow in Fixed-Width, Multi-Line Elements Using jQuery?. 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