use*_*660 4 html javascript css html-select
我试图使选择选项具有当前所选选项的宽度。
我的代码是选择选项下拉列表的标准 HTML:
<select name="search_options">
<option value="all">All</option>
<option value="entertainment">Entertainment</option>
<option value="newsandpolitics">News & Politics</option>
<option value="sports">Sports</option>
<option value="lifestyle">Lifestyle</option>
<option value="health">Health</option>
<option value="scienceandtech">Science & Tech</option>
</select>
Run Code Online (Sandbox Code Playgroud)
我一直在尝试仅使用 CSS 或 Javascript 来完成此操作,而不使用 JQuery,但我无法弄清楚。
我已经发现了一些 JQuery 的小提琴,但没有 CSS/Javascript 的。
有什么方法可以实现这一点,与上面的两个小提琴相同,仅使用CSS或纯Javascript?
任何指向正确方向的指针都会很棒。
小智 5
根据您的第二个链接,您可以这样做:
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";
}
Run Code Online (Sandbox Code Playgroud)
测试: http: //jsfiddle.net/ndquxquu/