gpt4 book ai didi

javascript - 调整选择框的大小以容纳所选文本

转载 作者:行者123 更新时间:2023-11-30 23:51:23 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com