Home > Article > Web Front-end > How to Implement Ellipsis in Text to Maintain Presence Amidst Width Fluctuation?
Ellipsis in Text: Maintaining Presence Amidst Width Fluctuation
In the realm of web design, the need arises to display ellipses ("...") within text that can span varying widths. This poses a challenge in achieving the desired behavior where the ellipsis disappears when the text width accommodates the full string.
To address this, a custom approach utilizing JavaScript and HTML can be implemented. Within the HTML element containing the text, the full string can be assigned to a data attribute, such as:
<span data-original="your string here"></span>
Once the page loads, a JavaScript function can be triggered to retrieve the original string from the data attribute and place it within the inner HTML of the span tag. Here is an example of an ellipsis function:
<code class="javascript">function start_and_end(str) { if (str.length > 35) { return str.substr(0, 20) + '...' + str.substr(str.length - 10, str.length); } return str; }</code>
This function truncates the string to a specific length (adjust as needed based on font size and desired spacing) and inserts the ellipsis in the middle.
As the element is resized, the resize event listener can trigger the ellipsis function to maintain the desired behavior. If necessary, the function parameters can be made dynamic to support different objects and text lengths.
To ensure accessibility across browsers, it's recommended to incorporate an abbr-tag within the ellipsis to provide a tooltip that displays the full string:
<abbr title="simple tool tip">something</abbr>
By integrating this JavaScript-based approach, the ellipsis can seamlessly appear and disappear as the element width fluctuates, ensuring visually appealing and functional text display in responsive designs.
The above is the detailed content of How to Implement Ellipsis in Text to Maintain Presence Amidst Width Fluctuation?. For more information, please follow other related articles on the PHP Chinese website!