如何使选定选项成为当前所选选项文本的宽度? [英] How to make the Selected Option the width of the current Selected Option's text?

查看:57
本文介绍了如何使选定选项成为当前所选选项文本的宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使Select Option具有当前Selected Option的宽度。

I am trying to make the Select Option to have the width of the current Selected Option.

我的代码是Select Option下拉列表的标准HTML:

My code is the standard HTML for a Select Option dropdown:

<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,我可以'弄明白。

I have been trying to do this with just CSS or Javascript, with no JQuery, and I can't figure it out.

我已经找到了几个有JQuery的小提琴,但没有CSS / Javascript小提琴。

I have found several fiddles with JQuery already, but no CSS/Javascript ones.

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

http://jsfiddle.net/qqcc5/

有没有办法实现这一点,与上面的2个小提琴相同,只使用CSS或纯Javascript?

Is there any way to achieve this, identical with the above 2 fiddles, using just CSS or pure Javascript?

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

Any pointers in the right direction would be great.

推荐答案

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

Based on your second link you can do it like this:

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";
}

测试:
http://jsfiddle.net/ndquxquu/

这篇关于如何使选定选项成为当前所选选项文本的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆