【问题标题】:How to change width of the select element as per the selected option?如何根据所选选项更改选择元素的宽度?
【发布时间】:2011-09-17 03:37:06
【问题描述】:

我有很大的下拉菜单列表。 一些选项有非常大的文本。我想根据所选选项制作所选元素的宽度。

如果选择的选项是“已选择”,那么宽度应该是 120px 之类的。 当用户选择“Very Large Selected option”时,<select> 标签的宽度应该增加。

这是我想要做的示例代码。 http://jsbin.com/axaka4/edit

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

使用一些作弊,您可以克隆所选选项的内容,测量它的宽度并将选择调整为这个宽度,如下所示:

$('select').change(function(){
    var $opt = $(this).find("option:selected");
    var $span = $('<span>').addClass('tester').text($opt.text());

    $span.css({
        'font-family' : $opt.css('font-family'),
        'font-style' : $opt.css('font-style'),
        'font-weight' : $opt.css('font-weight'),
        'font-size' : $opt.css('font-size')
    });

    $('body').append($span);
    // The 30px is for select open icon - it may vary a little per-browser
    $(this).width($span.width()+30);
    $span.remove();
});

$('select').change();

A working fiddle here

【讨论】:

【解决方案2】:

我还没有测试过,但我认为这应该可以工作。我假设你有多选下拉菜单

 $("selectId").change(function () { 
         $("selectid option:selected").each(function () { 
                str = $(this).width(); 
                $('#selectId').width(str); 
          }); 
});

【讨论】:

  • 不幸的是,选择选项的“宽度”似乎总是为零,所以你不能这样做,也不能使用 getBoundingRect。该死的HTML!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-11
  • 1970-01-01
  • 2011-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多