根据所选OPTION的宽度自动调整SELECT元素的大小

问题描述 投票:20回答:7

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

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

问题:

  • 在Chrome(Canary)上,它的返回宽度始终为0。
  • 在Firefox上,选择较短的选项时,会添加宽度并且不会调整大小。
  • Safari:与Chrome相同的结果。

Demo @ JSFiddle

jquery select resize autoresize dom-manipulation
7个回答
41
投票

你是对的,没有简单或内置的方法来获得特定选择选项的大小。这是一个JsFiddle做你想要的。

最新版本的Chrome, Firefox, IE, Opera and Safari没问题。

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

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

15
投票

这是我刚为this question写的一个插件,它动态创建并销毁了一个模拟span,因此它不会使你的HTML混乱。这有助于分离问题,允许您委派该功能,并允许跨多个元素轻松重用。

在任何地方都包含这个JS:

(function($, window){
  var arrowWidth = 30;

  $.fn.resizeselect = function(settings) {  
    return this.each(function() { 

      $(this).change(function(){
        var $this = $(this);

        // create test element
        var text = $this.find("option:selected").text();
        var $test = $("<span>").html(text).css({
            "font-size": $this.css("font-size"), // ensures same size text
            "visibility": "hidden"               // prevents FOUC
        });


        // add to parent, get width, and get out
        $test.appendTo($this.parent());
        var width = $test.width();
        $test.remove();

        // set select width
        $this.width(width + arrowWidth);

        // run on start
      }).change();

    });
  };

  // run by default
  $("select.resizeselect").resizeselect();                       

})(jQuery, window);

您可以通过以下两种方式之一初始化插件:

  1. HTML - 将类.resizeselect添加到任何select元素: <select class="btn btn-select resizeselect"> <option>All</option> <option>Longer</option> <option>A very very long string...</option> </select>
  2. JavaScript - 在任何jQuery对象上调用.resizeselect()$("select").resizeselect()

Here's a Demo in jsFiddle

Here's a Demo in Stack Snippets:

(function($, window){
  var arrowWidth = 30;

  $.fn.resizeselect = function(settings) {  
    return this.each(function() { 

      $(this).change(function(){
        var $this = $(this);

        // create test element
        var text = $this.find("option:selected").text();
        var $test = $("<span>").html(text).css({
        	"font-size": $this.css("font-size"), // ensures same size text
            "visibility": "hidden"               // prevents FOUC
        });
        
        // add to parent, get width, and get out
        $test.appendTo($this.parent());
        var width = $test.width();
        $test.remove();

        // set select width
        $this.width(width + arrowWidth);

        // run on start
      }).change();

    });
  };

  // run by default
  $("select.resizeselect").resizeselect();                       

})(jQuery, window);
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>

<select class="resizeselect">
  <option>All</option>
  <option>Longer</option>
  <option>A very very long string...</option>
</select>

Updated to include sizing suggestions from Garywoo & Eric Warnke


3
投票

尝试以下简单的JavaScript并在jQuery中转换它:)

<html><head><title>Auto size select</title>

<script>
var resized = false;

function resizeSelect(selected) {
  if (resized) return;
  var sel = document.getElementById('select');
  for (var i=0; i<sel.options.length; i++) {
    sel.options[i].title=sel.options[i].innerHTML;
    if (i!=sel.options.selectedIndex) sel.options[i].innerHTML='';
  }
  resized = true;
  sel.blur();
}

function restoreSelect() {
  if (!resized) return;
  var sel = document.getElementById('select');
  for (var i=0; i<sel.options.length; i++) {
    sel.options[i].innerHTML=sel.options[i].title;
  }  
  resized = false;
}
</script>

</head>
<body onload="resizeSelect(this.selectedItem)">
<select id="select" 
  onchange="resizeSelect(this.selectedItem)"
  onblur="resizeSelect(this.selectedItem)"
  onfocus="restoreSelect()">
<option>text text</option>
<option>text text text text text</option>
<option>text text text </option>
<option>text text text text </option>
<option>text</option>
<option>text text text text text text text text text</option>
<option>text text</option>
</select>
</body></html>

这是一个jsfiddle:https://jsfiddle.net/sm4dnwuf/1/

基本上它所做的是暂时删除未选中的元素(当它不在焦点上时(使其大小只是所选元素的大小)。


2
投票

这个工作解决方案在这里使用临时辅助select,其中克隆了主选择中的所选选项,以便可以评估主要select应具有的真实宽度。

这里的好处是你只需添加这个代码,它适用于每个选择,因此不需要ids和额外的命名。

$('select').change(function(){
  var text = $(this).find('option:selected').text()
  var $aux = $('<select/>').append($('<option/>').text(text))
  $(this).after($aux)
  $(this).width($aux.width())
  $aux.remove()
}).change()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
  <option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option>
  <option>ABCDEFGHIJKL</option>
  <option>ABC</option>
</select>

1
投票

你可以使用一个简单的功能:

// Function that helps to get the select element width.
$.fn.getSelectWidth = function() {
  var width = Math.round($(this).wrap('<span></span>').width());
  $(this).unwrap();
  return width;
}

然后在表单选择元素上使用它:

$(this).getSelectWidth();

1
投票

这是另一个简单的jQuery解决方案:

$('#mySelect').change(function(){
    var $selectList = $(this);

    var $selectedOption = $selectList.children('[value="' + this.value + '"]')
        .attr('selected', true);
    var selectedIndex = $selectedOption.index();

    var $nonSelectedOptions = $selectList.children().not($selectedOption)
        .remove()
        .attr('selected', false);

    // Reset and calculate new fixed width having only selected option as a child
    $selectList.width('auto').width($selectList.width());

    // Add options back and put selected option in the right place on the list
    $selectedOption.remove();
    $selectList.append($nonSelectedOptions);
    if (selectedIndex >= $nonSelectedOptions.length) {
         $selectList.append($selectedOption);
    } else {
         $selectList.children().eq(selectedIndex).before($selectedOption);
    }
});

-3
投票

你也可以尝试一下

select option{width:0; }
select option:hover{width:auto;}
© www.soinside.com 2019 - 2024. All rights reserved.