Home > Web Front-end > CSS Tutorial > How Can I Detect CSS Text Overflow Using JavaScript?

How Can I Detect CSS Text Overflow Using JavaScript?

Mary-Kate Olsen
Release: 2024-12-17 00:11:25
Original
431 people have browsed it

How Can I Detect CSS Text Overflow Using JavaScript?

Detecting Text Overflow with Ellipsis

The text-overflow property in CSS allows text to be truncated when it exceeds the width of its container. An ellipsis (...) is then displayed to indicate that the text is cut off.

Overflow Detection

To detect which elements on a webpage have their text truncated, you can use JavaScript:

function isEllipsisActive(e) {
    return (e.offsetWidth < e.scrollWidth);
}
Copy after login

This function takes an element as input and returns true if its width is less than its scroll width, indicating that its text is overflowing.

Example Usage

You can use this function to check the overflow status of an element, such as the following:

<div>
  <span>Normal text</span>
</div>
<div>
  <span>Long text that will be trimmed text</span>
</div>
Copy after login
console.log(isEllipsisActive(document.querySelector('span'))); // false (for the first div)
console.log(isEllipsisActive(document.querySelectorAll('span')[1])); // true (for the second div)
Copy after login

By using this JavaScript function, you can dynamically detect elements with overflowing text and apply appropriate styling or behavior accordingly.

The above is the detailed content of How Can I Detect CSS Text Overflow Using JavaScript?. 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