2011-06-17 95 views
3

我有大量的下拉菜單。 某些選項的文字非常大。我想根據選定的選項製作所選元素的寬度。如何根據選定的選項更改選擇元素的寬度?

如果選定的選項是「選定」,那麼寬度應該是120像素或什麼的。 當用戶選擇「Very Large Selected」選項時,<select>標籤的寬度應該增加。

下面是示例代碼,我正在嘗試做什麼。 http://jsbin.com/axaka4/edit

+0

參見http://stackoverflow.com/questions/2009 1481/auto-resizing-select-element-according-to-selected-options-width – rogerdpack 2017-04-21 19:17:22

回答

12

使用一些欺騙你能克隆所選擇的選項的內容,衡量它的寬度和調整大小選擇這個寬度是這樣的:

$('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

+0

不錯的想法.. :)愛它..謝謝你的例子。 – 2011-06-17 13:08:32

-1

我沒有測試過,但我想這應該幹活。我假設你有多項選擇的下拉

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

不幸的是,選擇選項的寬度總是爲零,所以你不能這樣做,也不能使用getBoundingRect。當HTML! – rogerdpack 2017-04-21 19:16:48