我正在使用 Javascript 向下拉列表动态添加新选项,当列表恢复为所选项目时,右侧的箭头会展开列表,包含所选文本的框与最宽的文本一样宽选项列表。
因此,如果您知道我的意思,而框内文本右侧没有多余的空白,我想做的是让框的宽度紧贴文本。
如果有人可以帮助我,非常感谢:-)
我正在使用 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>