Javascript 根据选定选项的宽度调整选定元素的宽度

Javascript 根据选定选项的宽度调整选定元素的宽度,javascript,jquery,twitter-bootstrap,twitter-bootstrap-3,html-select,Javascript,Jquery,Twitter Bootstrap,Twitter Bootstrap 3,Html Select,我希望select元素具有较短的默认选项值宽度。当用户选择另一个选项时,select元素应自行调整大小,以便整个文本在元素中始终可见 我在这个问题上找到了一个解决方案,但它不适用于引导,我也不知道为什么 以下是我的尝试: $document.readyfunction{ $'select'.change函数{ $width\u tmp.html$'select option:selected'。文本; //30:选择框向下箭头的大小 $this.width$width\u tmp.width+

我希望select元素具有较短的默认选项值宽度。当用户选择另一个选项时,select元素应自行调整大小,以便整个文本在元素中始终可见

我在这个问题上找到了一个解决方案,但它不适用于引导,我也不知道为什么

以下是我的尝试:

$document.readyfunction{ $'select'.change函数{ $width\u tmp.html$'select option:selected'。文本; //30:选择框向下箭头的大小 $this.width$width\u tmp.width+30; }; }; .btn选择{ 颜色:333; 背景色:F5; 边框颜色:ccc; 填充:7px; } 挑选{ 宽度:60px; } 宽度{ 显示:无; } 全部的 比较长的 一根很长的绳子。。。
出现此问题的原因是宽度\u tmp嵌套在.input组btn下,因此它继承了字体大小:0;属性从引导。因此,元素的计算宽度始终为零:

要解决此问题,只需移动,使其不在输入组内

纯JS解决方案 //初始加载时调整大小 document.querySelectorAllselect.forEachresizeSelect //更改的委托侦听器 document.body.addEventListenerchange,e=>{ 如果e.target.matchesselect{ resizeSelecte.target } } 功能调整SelectSell{ 让tempOption=document.createElement'option'; tempOption.textContent=sel.selectedOptions[0].textContent; 让tempSelect=document.createElement'select'; tempSelect.style.visibility=隐藏; tempSelect.style.position=固定 tempSelect.appendChildtempOption; 选择后选择; sel.style.width=`${+tempSelect.clientWidth+4}px`; tempSelect.remove; } 演示和堆栈代码段 //初始加载时调整大小 document.querySelectorAllselect.forEachresizeSelect //更改的委托侦听器 document.body.addEventListenerchange,e=>{ 如果e.target.matchesselect{ resizeSelecte.target } } 功能调整SelectSell{ 让tempOption=document.createElement'option'; tempOption.textContent=sel.selectedOptions[0].textContent; 让tempSelect=document.createElement'select'; tempSelect.style.visibility=隐藏; tempSelect.style.position=固定 tempSelect.appendChildtempOption; 选择后选择; sel.style.width=`${+tempSelect.clientWidth+4}px`; tempSelect.remove; } 一些更长的选择 空头期权 一个包含大量文本的很长的选项 短期选择2 一些更长的选项2 包含大量文本的很长选项2
当您将select的宽度设置为auto,然后在选项上设置宽度时会发生什么情况?非常感谢@KyleMit:第一行需要从function$,window{更改为$function$,window{,这相当于说$document.ready{function$,window}{否则,您的类属性只有在单击页面上的链接后才会更改,因为文档将在脚本执行后加载。我建议将var$test=$.htmltext;行更改为var$test=$.htmltext;,以确保创建的临时跨距的字体大小与select元素的字体大小匹配。如果跨度越小或越大,动态调整大小将被大小差异抵消。我建议不仅将“字体大小”设置为@Garywoo Suggested,还可以检索window.getComputedStylethis,并为跨度指定相同的字体大小、字体系列和行高。下面是一个更现代的vanilla JS方法请注意: