Make multiple-select to adjust its height to fit o

2019-01-21 21:21发布

Apparently this doesn't work:

   select[multiple]{
     height: 100%;
   }

it makes the select have 100% page height...

auto doesn't work either, I still get the vertical scrollbar.

Any other ideas?

enter image description here

13条回答
smile是对你的礼貌
2楼-- · 2019-01-21 21:49

Old, but this will do what you're after without need for jquery. The hidden overflow gets rid of the scrollbar, and the javascript makes it the right size.

<select multiple='multiple' id='select' style='overflow:hidden'>
<option value='foo'>foo</option>
<option value='bar'>bar</option>
<option value='abc'>abc</option>
<option value='def'>def</option>
<option value='xyz'>xyz</option>
</select>

And just a tiny amount of javascript

var select = document.getElementById('select');
select.size = select.length;
查看更多
三岁会撩人
3楼-- · 2019-01-21 21:51

I guess you can use the size attribute. It works in all recent browsers.

<select name="courses" multiple="multiple" size="30" style="height: 100%;">
查看更多
一夜七次
4楼-- · 2019-01-21 21:51

Using the size attribute is the most practical solution, however there are quirks when it is applied to select elements with only two or three options.

  • Setting the size attribute value to "0" or "1" will mostly render a default select element (dropdown).
  • Setting the size attribute to a value greater than "1" will mostly render a selection list with a height capable of displaying at least four items. This also applies to lists with only two or three items, leading to unintended white-space.

Simple JavaScript can be used to set the size attribute to the correct value automatically, e.g. see this fiddle.

$(function() {
    $("#autoheight").attr("size", parseInt($("#autoheight option").length)); 
});

As mentioned above, this solution does not solve the issue when there are only two or three options.

查看更多
叛逆
5楼-- · 2019-01-21 21:54

friends: if you retrieve de data from a DB: you can call this $registers = *_num_rows( Result_query ) then

<select size=<?=$registers + 1; ?>"> 
查看更多
We Are One
6楼-- · 2019-01-21 21:56

You can do this with simple javascript...

<select multiple="multiple" size="return this.length();">

...or limit height until number-of-records...

<select multiple="multiple" size="return this.length() > 10 ? this.length(): 10;">
查看更多
做自己的国王
7楼-- · 2019-01-21 21:57

For jQuery you can try this. I always do the following and it works.

$(function () {
   $("#multiSelect").attr("size",$("#multiSelect option").length);
});
查看更多
登录 后发表回答