在选择框选项中设置宽度

Mah*_*buj 13 css html-select

在此输入图像描述

在图片中,选项的宽度大于选择框.我想将这些选项的宽度设置为与选择框相同,对于那些较大的选项,将text-overflow设置为省略号.任何帮助,将不胜感激.

这是我尝试过的:

HTML

<select>
    <option>Select your University</option>
    <option>Bangladesh University of Engineering and Technology</option>
    <option>Mawlana Bhashani Science and Technology University</option>
</select>
Run Code Online (Sandbox Code Playgroud)

CSS

select, option {
    width: 250px;
}

option {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
Run Code Online (Sandbox Code Playgroud)

小提琴:https://jsfiddle.net/3bsbcqfz/

din*_*ndu 9

我试图从CSS找到解决方案.但我没能做到.没关系,我已经为它写了一个简单的javascript代码.这可以为它做点什么.

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');
};
Run Code Online (Sandbox Code Playgroud)
select {
  width: 250px;
}

option {
  width: 250px;
}
Run Code Online (Sandbox Code Playgroud)
<select name="select" id="select">
  <option class='short' data-limit='37' value="Select your University">Select your University</option>
  <option class='short' data-limit='37' value="Bangladesh University of Engineering and Technology">Bangladesh University of Engineering and Technology</option>
  <option class='short' data-limit='37' value="Mawlana Bhashani Science and Technology University">Mawlana Bhashani Science and Technology University</option>
</select>
Run Code Online (Sandbox Code Playgroud)


ell*_*sis 5

您可以使用 javascript 来缩短选项文本的长度,以使其与选项的长度相匹配。我找不到仅使用 css 的解决方案

var e=document.querySelectorAll('option')
e.forEach(x=>{
if(x.textContent.length>20)
x.textContent=x.textContent.substring(0,20)+'...';
})
Run Code Online (Sandbox Code Playgroud)
select
{
width:160px;
}
Run Code Online (Sandbox Code Playgroud)
<select>
<option>fwefwefwefwe</option>
<option>fwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwe</option>
</select>
Run Code Online (Sandbox Code Playgroud)