根据所选选项的宽度自动调整 SELECT 元素的大小 [英] Auto resizing the SELECT element according to selected OPTION's width

查看:60
本文介绍了根据所选选项的宽度自动调整 SELECT 元素的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 select 元素,其中包含不同的 option.通常 select 元素会从最大的 option 元素获取其宽度,但我希望 select 元素具有默认的 option 值的宽度较短.当用户选择另一个 option 时,select 元素应该调整自身大小,以便整个文本始终在元素中可见.

I've got this select element with different option in it. Normally the select element would get its width from the biggest option element, but I want the select element to have the default option value's width which is shorter. When the user selects another option, the select element should resize itself so the whole text is always visible in the element.

$(document).ready(function() {
    $('select').change(function(){
        $(this).width($('select option:selected').width());
    });
});

问题:

  • 在 Chrome (Canary) 上,它总是返回 0 的宽度.
  • firefox上的
  • 在选择更短的选项时,宽度已添加,而未调整大小.
  • Safari:结果与 Chrome 相同.

演示@JSFiddle

推荐答案

您说得对,没有简单或内置的方法可以获取特定选择选项的大小.这是一个 JsFiddle 可以满足您的需求.

You are right there is no easy or built-in way to get the size of a particular select option. Here is a JsFiddle that does what you want.

最新版本的 Chrome、Firefox、IE、Opera 和 Safari 都可以.

It is okay with the latest versions of Chrome, Firefox, IE, Opera and Safari.

我添加了一个隐藏的选择 #width_tmp_select 来计算我们想要自动调整大小的可见选择 #resizing_select 的宽度.我们将隐藏的选择设置为具有单个选项,其文本是可见选择的当前选择的选项的文本.然后我们使用隐藏选择的宽度作为可见选择的宽度.请注意,使用隐藏的跨度而不是隐藏的选择效果很好,但正如 sami-al-subhi 在下面的评论中指出的那样,宽度会稍微偏离.

I have added a hidden select #width_tmp_select to compute the width of the visible select #resizing_select that we want to be auto resizing. We set the hidden select to have a single option, whose text is that of the currently-selected option of the visible select. Then we use the width of the hidden select as the width of the visible select. Note that using a hidden span instead of a hidden select works pretty well, but the width will be a little off as pointed out by sami-al-subhi in the comment below.

$(document).ready(function() {
  $('#resizing_select').change(function(){
    $("#width_tmp_option").html($('#resizing_select option:selected').text()); 
    $(this).width($("#width_tmp_select").width());  
  });
});

#resizing_select {
  width: 50px;
} 
 
#width_tmp_select{
  display : none;
} 

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>

<select id="resizing_select">
  <option>All</option>
  <option>Longer</option>
  <option>A very very long string...</option>
</select>

<select id="width_tmp_select">
  <option id="width_tmp_option"></option>
</select>

这篇关于根据所选选项的宽度自动调整 SELECT 元素的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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