Home > Article > Web Front-end > How to Display Tooltips Only When Text is Ellipsized in HTML?
In HTML, when text exceeds the specified width, it gets truncated with an ellipsis ("..."). This can be achieved using the text-overflow property set to ellipsis. However, it lacks browser support for detecting when ellipsis is applied.
Custom Event Handling with JavaScript
To simulate this behavior and display tooltips only when ellipsis is present, here's a JavaScript approach:
<code class="javascript">$('.mightOverflow').bind('mouseenter', function() { var $this = $(this); if (this.offsetWidth < this.scrollWidth && !$this.attr('title')) { $this.attr('title', $this.text()); } });</code>
This code binds the mouseenter event to elements that may overflow. It checks if the element's visible width (offsetWidth) is less than its actual content width (scrollWidth) and if it doesn't have a title attribute. If these conditions are met, it sets the title attribute to the element's text content.
This technique allows you to display tooltips only when the ellipsis is activated without relying on specific browser events.
The above is the detailed content of How to Display Tooltips Only When Text is Ellipsized in HTML?. For more information, please follow other related articles on the PHP Chinese website!