Home > Web Front-end > JS Tutorial > 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
Release: 2024-10-26 08:48:03
Original
541 people have browsed it

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)*$/, '...');
    });
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template