How to give scrolling effect in datalist dropdown?

2020-02-13 13:13发布

问题:

I am using HTML datalist to show various career paths but my number of options is too long . I wish to give it a scrolling effect. I have searched for it but only thing I found was CSS cannot be applied on datalist. Is it possible to apply styles on datalist using jQuery?

Here is my HTML markup:

<input class="form-control searchbar" #input (input)="filterdata(input.value)" [(ngModel)]="homesearch" id="home_ssearch" name="careerr" list="careers" placeholder="Discover more about any career you like" />
<div>
        <datalist class="datalist" id="careers" >
          <option *ngFor = "let career of carrerpathList" value="{{career.title}}" ></option>         
        </datalist>
</div>

回答1:

In general, you can't. This element is an example of a "replaced element", these are OS-dependent and are not part of the HTML/browser. It cannot be styled via CSS.

Instead you can use bootstrap dropdown or any other plugin for the same.

I have used bootstrap for it, you can adjust the height accordingly for e.g,

.dropdown-menu {
  max-height: 150px;
  overflow-y: auto;
}

jsfiddle link



回答2:

Try this

.scrollable {
  overflow-y: auto !important;  // Use !important only if there is already an overflow style rule for this element and you want to override
}

And just apply it like this:

<datalist class="datalist scrollable" id="careers" >
     <option *ngFor = "let career of carrerpathList" value="{{career.title}}" ></option>         
</datalist>

Hope it helps! ;)

Update 1:

I hate inline styles, but let's try it to see if <datalist> accepts styles. Try this:

<datalist class="datalist scrollable" id="careers" style="overflow-y: auto!important">


回答3:

try this:

.datalist {
   height:50px !important;
   max-height:80px !important;
   overflow-y:auto;
   display:block !important;
}


回答4:

This simple approach works for me:

datalist {
    max-height: 500px;
    overflow-y: auto;
}

Note: This CSS will apply the scroll effect to all <datalist>



标签: html angular