我正在使用 Javascript 动态地将新选项添加到下拉列表中,当列表恢复为所选项目并使用其右侧的箭头展开列表时,包含所选文本的框与选项列表中最宽的文本。
所以我想做的是让框的宽度拥抱文本,如果你知道我的意思,并且框内文本右侧没有多余的空白。
如果有人能帮助我,非常感谢:-)
最佳答案
很简单,只需删除隐藏选项的内容(将其复制到选项的标题中)并在选择焦点时恢复它即可。
代码:
<html><head><title>Auto size select</title>
<script>
var resized = false;
function resizeSelect(selected) {
if (resized) return;
var sel = document.getElementById('select');
for (var i=0; i<sel.options.length; i++) {
sel.options[i].title=sel.options[i].innerHTML;
if (i!=sel.options.selectedIndex) sel.options[i].innerHTML='';
}
resized = true;
sel.blur();
}
function restoreSelect() {
if (!resized) return;
var sel = document.getElementById('select');
for (var i=0; i<sel.options.length; i++) {
sel.options[i].innerHTML=sel.options[i].title;
}
resized = false;
}
</script>
</head>
<body onload="resizeSelect(this.selectedItem)">
<select id="select"
onchange="resizeSelect(this.selectedItem)"
onblur="resizeSelect(this.selectedItem)"
onfocus="restoreSelect()">
<option>text text</option>
<option>text text text text text</option>
<option>text text text </option>
<option>text text text text </option>
<option>text</option>
<option>text text text text text text text text text</option>
<option>text text</option>
</select>
</body></html>
关于javascript - 调整选择框的大小以容纳所选文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1451267/