如何使所选选项的宽度等于当前所选选项文本的宽度?

2023-11-30

我试图使选择选项具有当前所选选项的宽度。

我的代码是选择选项下拉列表的标准 HTML:

<select name="search_options">
  <option value="all">All</option>
  <option value="entertainment">Entertainment</option>
  <option value="newsandpolitics">News &amp; Politics</option>
  <option value="sports">Sports</option>
  <option value="lifestyle">Lifestyle</option>
  <option value="health">Health</option>
  <option value="scienceandtech">Science &amp; Tech</option>
</select>

我一直在尝试仅使用 CSS 或 Javascript 来完成此操作,而不使用 JQuery,但我无法弄清楚。

我已经发现了一些 JQuery 的小提琴,但没有 CSS/Javascript 的。

http://jsfiddle.net/5AANG/4/

http://jsfiddle.net/qqcc5/

有什么方法可以实现这一点,与上面的两个小提琴相同,仅使用CSS或纯Javascript?

任何指向正确方向的指针都会很棒。


根据您的第二个链接,您可以这样做:

var selectId = document.getElementById("yourSelect");

selectId.onchange=function(){
   var selectedValue = selectId.options[selectId.selectedIndex].value; 
   var selectedText = selectId.options[selectId.selectedIndex].text;

   selectId.style.width = 20 + (selectedText.length * 8) + "px";
}

Test: http://jsfiddle.net/ndquxquu/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使所选选项的宽度等于当前所选选项文本的宽度? 的相关文章

随机推荐