在选择框选项中设置宽度 [英] Set Width at Option of Select Box
本文介绍了在选择框选项中设置宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在图片中,选项的宽度大于选择框.我想将这些选项的宽度设置为与选择框相同对于那些较大的选项,请将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;
}
小提琴: https://jsfiddle.net/3bsbcqfz/ >
推荐答案
我试图从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>
这篇关于在选择框选项中设置宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文