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

Javascript 调整选择框的大小以容纳所选文本,javascript,selection,Javascript,Selection,我正在使用Javascript向下拉列表中动态添加新选项,当列表恢复为选定项并在其右侧使用箭头展开列表时,包含选定文本的框与选项列表中最宽的文本一样宽 如果你知道我的意思的话,我想做的是让框的宽度与文本相吻合,而不需要在框中文本的右边留多余的空白 非常感谢,如果有人能帮我:-)很简单,只需删除隐藏选项的内容(将其复制到选项标题中)并在选择焦点时恢复即可 代码: 自动选择大小 var resized=false; 函数大小选择(选定){ 如果(调整大小)返回; var sel=document.g

我正在使用Javascript向下拉列表中动态添加新选项,当列表恢复为选定项并在其右侧使用箭头展开列表时,包含选定文本的框与选项列表中最宽的文本一样宽

如果你知道我的意思的话,我想做的是让框的宽度与文本相吻合,而不需要在框中文本的右边留多余的空白


非常感谢,如果有人能帮我:-)

很简单,只需删除隐藏选项的内容(将其复制到选项标题中)并在选择焦点时恢复即可

代码:

自动选择大小
var resized=false;
函数大小选择(选定){
如果(调整大小)返回;
var sel=document.getElementById('select');

对于(var i=0;i很简单,只需删除隐藏选项的内容(将其复制到选项的标题中)并将其恢复到选择焦点即可

代码:

自动选择大小
var resized=false;
函数大小选择(选定){
如果(调整大小)返回;
var sel=document.getElementById('select');

对于(var i=0;iI)来说,从OnBlur事件开始:因此,当用户完成选择后,是时候显示他们的选择了。因此,现在我需要调整选择框的宽度以匹配所选文本。我猜这将涉及DOM,因此我们可以这样做:var sel=document.getElementById(“DropDownList”);并从那里开始工作。但我对这种DOM操作是新手。我从OnBlur事件开始:因此,当用户完成选择后,是时候显示他们的选择了。因此,现在我需要调整选择框的宽度以匹配所选文本。我猜这将涉及DOM,因此我们可以执行:var sel=document.getElementById(“DropDownList”);并从那里开始工作。但我对这种DOM操作还不熟悉。谢谢Pedro!酷解决方案:-)谢谢Pedro!酷解决方案:-)
<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>