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

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

问题描述

我有一个带有不同optionselect元素.通常,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(金丝雀)上,宽度总是返回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 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>

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

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