Limiting options in select dropdown to a specific

2019-09-14 22:16发布

问题:

I have a dropdown list, of the options in dropdown list is less than or equal to 10 this will display all the available options but if the number of options is more than 10 then the options list should have a vertical scroll bar.

<select>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
    <option>6</option>
</select>

回答1:

HTML Code

<select onmousedown="if(this.options.length>15){this.size=15;}" onchange='this.size=0;' onblur="this.size=0;">
 <option>1</option>
 <option>2</option>
 <option>3</option>
 <option>4</option>
 <option>5</option>
 <option>6</option>
 <option>7</option>
 <option>8</option>
 <option>9</option>
 <option>10</option>
 <option>11</option>
 <option>12</option>
 <option>13</option>
 <option>14</option>
 <option>15</option>
 <option>16</option>
 <option>17</option>
 <option>18</option>
 <option>19</option>
 <option>20</option>
 <option>21</option>
 <option>22</option>
 <option>23</option>
 <option>24</option>
 <option>25</option>
</select>

Please check the working fiddle: Demo



回答2:

As gcampbell noted, this is the job of the browser and cannot be influenced. If you want it to style, you have to create your own menu. For example:

<div id="menu">
<p>1</p>
...
</div>

p{height:10px}
#menu{height:100px;overflow:scroll;}