Is it possible to style the drop-down suggestions when using HTML5 <datalist>?

半城伤御伤魂 提交于 2019-12-03 22:10:09
Android334

From the best of my knowledge you cannot style the <datalist> tag. I recommend using the JQuery extension autocomplete. So you're need to include JQuery in your html document. here is a link hosted by Google: See here

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script

Note: you can get better performance by including this at the end of the document and using $(document).ready();

For example:

HTML:

<input type='text' id='input'>

Javascript:

$(document).ready(function() {
    var arrayOfOptions = [
        "Option 1",
        "Option 2",
        "etc"
    ];

    $("#input").autocomplete({source: arrayOfOptions});
});

note: not tested code!

Source: http://jqueryui.com/autocomplete/

You can style this similarly to how you style a nav. Here are some classes you can style:

.ui-autocomplete span.hl_results {background-color: #ffff66;}
.ui-autocomplete-loading {} //the object while it's loading (in the event of Ajax, in this case would not need this one
.ui-autocomplete {
    max-height: 250px;
    overflow-y: auto;
    overflow-x: hidden;
    padding-right: 5px;
}

.ui-autocomplete li {font-size: 16px;}
html .ui-autocomplete {
    height: 250px;
}

Styling datalist with CSS only is not possible across browsers. Internet Explorer, Firefox, Chrome and Edge apply basic styling to the input[list] element, but neither to datalist, nor to its option child elements.

See CodePen example.

Citing from MDN “Styling HTML forms – the ugly”:

Some elements simply can't be styled using CSS. These include: all advanced user interface widgets, such as range, color, or date controls; and all the dropdown widgets, including <select>, <option>, <optgroup> and <datalist> elements.

A very common way to circumvent this UI limitation is to provide a JavaScript based widget, that falls back to the HTML5 input+datalist combination for users which have JS disabled.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!