更改默认选择下拉菜单外观

时间:2018-06-29 03:30:38

标签: javascript html css select

让我看看我有一个选择:

<select class="selectpicker">
  <option selected> A </option>
  <option> B </option>
  <option> C </option>
</select>

查看选项时,如何更改下拉菜单中显示的项目的外观?

我的直觉是您会隐藏默认选项并使用自己的CSS或/和JavaScript填充新列表吗?

Going from the default style like this: Click on link to view:

To a nice look like this: Click on the link to view

1 个答案:

答案 0 :(得分:0)

jQuery

$(document).ready(function(e){

$(".DropdownWrapper").focusin(function(e){

    $(".Dropdown").css('display', 'block');

});

$(".Item").click(function(e){

    var val = $(this).text();

    $(".Textfield").val(val);

    $(".Dropdown").css('display', 'none');

});

});

HTML

<div class="Content">

<h1>Custom Dropdown Menu For a Textfield By Farris</h1>

<div class="DropdownWrapper">
    <input type="text" class="Textfield" placeholder="Animal" />
    <div class="Dropdown">
        <div class="Item">Lion</div>
        <div class="Item">Cat</div>
        <div class="Item">Dog</div>
        <div class="Item">Monkey</div>
    </div>
</div>

</div>

CSS

body{
    background-color: #222;
    color: #FFF;
    font-family: sans-serif;
    margin: 0px;
}

.Content{
    width: 800px;
    height: auto;
    overflow: visible;
    margin: 30px auto;
}

.Textfield{
    width: 220px;
    height: 20px;
    background-color: #111;
    color: #FFF;
    font-family: sans-serif;
    padding: 15px;
    border: none;
    outline: none;
    border-radius: 3px;
}

.DropdownWrapper{
    width: 250px;
    height: 50px;
    position: relative;
    margin-bottom: 10px;
}

.Dropdown{
    position: absolute;
    top: 50px;
    left: 0px;
    width: 250px;
    height: auto;
    overflow: visible;
    z-index: 1;
    display: none;
}

.Item{
    width: 220px;
    height: 20px;
    padding: 15px;
    color: #CCC;
    background-color: #111;
}

.Item:hover{
    background-color: #000;
    cursor: pointer;
    color: #FFF;
}

此代码段适用于文本字段和按钮