首页 > 解决方案 > How to construct a bootstrap dropdown list with static placeholder and custom icon

问题描述

I'm very new to web development and I'm trying to construct a dropdown list that contains a static, slightly greyed out, placeholder and a custom icon. When an item in the drop down list is selected, the text of the selected item should be displayed on the dropdown. I have tried a few different approaches and the code below gets me somewhat close but still not exactly what I'm looking for and I'm also not even sure if this is the right approach.

Is there a way to create a bootstrap (or non bootstrap) dropdown with a static placeholder, custom icon, and updates display text to user selection?

<div>
  <label type = "button">Fruit</label>
  <div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown button
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    <a class="dropdown-item" href="#">Apple</a>
    <a class="dropdown-item" href="#">Blueberry</a>
    <a class="dropdown-item" href="#">Pear</a>
  </div>
</div>
</div>

enter image description here

标签: javascriptjqueryhtmlcssbootstrap-4

解决方案


请将此片段视为可能的答案。

$(".dropdown-item").click(function(){
  $(".dropdown-item").removeClass("active");
  $("#dropdownMenuLabel").text(this.innerHTML);
  $(this).addClass("active");
});
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    <span class="text-dark">Fruit</span> <span id="dropdownMenuLabel"></span>
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    <a class="dropdown-item" href="#">Apple</a>
    <a class="dropdown-item" href="#">Blueberry</a>
    <a class="dropdown-item" href="#">Pear</a>
  </div>
</div>


推荐阅读