"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Control the Width of Select Box Options and Implement Text Ellipsis?

How to Control the Width of Select Box Options and Implement Text Ellipsis?

Published on 2024-11-13
Browse:429

How to Control the Width of Select Box Options and Implement Text Ellipsis?

Controlling the Width of Select Box Options

In HTML, by applying style attributes to both the select element and its child option elements, it's possible to specify the width of each option to ensure it matches the select box width. However, achieving this with CSS alone may not be sufficient.

One solution involves incorporating JavaScript to further control the option width and enable text ellipsis when necessary. The provided JavaScript code introduces a shortString function that dynamically adjusts the text within option elements having the .short class and the data-limit attribute.

Here's how to implement this solution:



select {
  width: 250px;
}

option {
  width: 250px;
}

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

This approach ensures that the option width is identical to the select box width, and when the option text exceeds the specified limit, the excess text is replaced with an ellipsis.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3