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
Mary-Kate OlsenOriginal
2024-12-17 00:11:25467browse

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);
}

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>
console.log(isEllipsisActive(document.querySelector('span'))); // false (for the first div)
console.log(isEllipsisActive(document.querySelectorAll('span')[1])); // true (for the second div)

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!

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