Home >Web Front-end >CSS Tutorial >How can I control the width of select box options and implement text overflow ellipsis using JavaScript?
Controlling the Width of Select Box Options
In your select box, the options are visually wider than the box itself, creating a misalignment. To rectify this, you aim to set the width of the options equal to that of the box. Additionally, you wish to implement text overflow ellipsis for options with lengthy text.
Conventional CSS Approach
Initially, you attempted a solution using CSS, which proved futile. CSS alone does not provide a means to directly control the width of options within a select box.
JavaScript Intervention
Since CSS could not offer a solution, you sought an alternative in JavaScript. The JavaScript code you provided successfully modifies the text width of options within the select box. It works by iterating over each option element and modifying its inner text if necessary.
HTML and CSS Modifications
In your HTML, you added the data-limit attribute to each option element to specify the maximum text length allowed. In your CSS, you set a fixed width of 250px for both the select box and the options.
Code Snippet
Here's a snippet of the JavaScript code:
function shortString(selector) { const elements = document.querySelectorAll(selector); const tail = '...'; if (elements && elements.length) { for (const element of elements) { let text = element.innerText; if (element.hasAttribute('data-limit')) { if (text.length > element.dataset.limit) { element.innerText = `${text.substring(0, element.dataset.limit - tail.length).trim()}${tail}`; } } else { throw Error('Cannot find attribute \'data-limit\''); } } } } window.onload = function() { shortString('.short'); };
Demo
When you run this script, options with a text length greater than the specified limit will be truncated with an ellipsis, ensuring that they fit within the select box width.
The above is the detailed content of How can I control the width of select box options and implement text overflow ellipsis using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!