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

标签 javascript selection

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

相关文章:

xcode - 如何在 Xcode 中更改失焦文本选择颜色?

android - 图库小部件的自定义边框

安卓。 charAt (setSelection) 中的奇怪崩溃

javascript - jquery 调用 get 或 post 很慢

javascript - JQuery 滑动开关 :visible conditional

javascript - Electron 类型错误: Cannot read property 'normalizePath' of undefined

textarea - 如何知道用户在 JavaFX TextArea 中选择了哪个文本字符串

javascript - 最佳实践 - BackBone JS - 模型 View 关系

javascript - 在 Chrome 和 Mozilla 中显示选择上传的图像

java - JTextField/JTextComponent 中的选择有限?