在选择框选项中设置宽度
问题描述:
在图片中,选项的宽度大于选择框.我想将这些选项的宽度设置为与选择框相同对于那些较大的选项,请将text-overflow设置为省略号.任何帮助将不胜感激.
In the picture, the width of option is larger than the select box. I want to set width of those options as same as select box & for those larger options set text-overflow as ellipsis. Any help would be appreciated.
这是我尝试过的:
HTML
<select>
<option>Select your University</option>
<option>Bangladesh University of Engineering and Technology</option>
<option>Mawlana Bhashani Science and Technology University</option>
</select>
Css
select, option {
width: 250px;
}
option {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
答
我试图从CSS中找到一种解决方案.但是我做不到.没关系,我已经为它编写了一个简单的javascript代码.这可以为它做点什么.
I tried to find a solution from CSS. But I failed to do it. Doesn't matter, I have written a simple javascript code for it. This is can do it something for it.
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');
};
select {
width: 250px;
}
option {
width: 250px;
}
<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>