带有复选框的多个下拉菜单

时间:2020-03-29 06:21:16

标签: jquery html css

我创建了一个多选下拉菜单,用户可以通过单击每个选项的复选框来选择选项。它仅适用于这样的下拉菜单,但我需要在一页上包含许多这样的下拉菜单。有谁知道如何更改代码来实现这一目标?

这是此https://codepen.io/chaser7016/pen/yLNGWYb的代码笔。在下面,我还添加了在代码笔中看到的html / css / jquery。

$('.dropdown-container')
  .on('click', '.dropdown-button', function() {
        $(this).siblings('.dropdown-list').toggle();
  })
  .on('input', '.dropdown-search', function() {
      var target = $(this);
        var dropdownList = target.closest('.dropdown-list');
      var search = target.val().toLowerCase();
    
      if (!search) {
            dropdownList.find('li').show();
            return false;
        }
    
      dropdownList.find('li').each(function() {
          var text = $(this).text().toLowerCase();
            var match = text.indexOf(search) > -1;
            $(this).toggle(match);
        });
  })

  $('.dropdown-list input[type="checkbox"]').on('click', function () {
        
          var title = $(this).closest('.dropdown-list').find('input[type="checkbox"]').val(),
              title = $(this).val() + ",";
        
          if ($(this).is(':checked')) {
              var html = '<span title="' + title + '">' + title + '</span>';
              $('.quantity').append(html);
              $(".hida").hide();
          } 
          else {
              $('span[title="' + title + '"]').remove();
              var ret = $(".hida");
              $('.dropdown dt a').append(ret);
              
          }
      });
.dropdown-button {
    width: 100%;
    background: white;
    cursor: pointer;
    padding: 19px;
    box-sizing: border-box;
    border: 1px solid;
  }
    .dropdown-label, .dropdown-quantity {
        float: left;
        font-family: 'Ubuntu', sans-serif;
    }
    
    .dropdown-quantity {
        margin-left: 4px;
    }

    input[type="search"] {
        padding: 5px;
        width: 100%;
        margin: 3px 0 8px;
    }
    
    .dropdown-list {
        margin: 0;
        overflow-y: auto;
        border-bottom: 1px solid #d5d5d5;
        border-left: 1px solid #d5d5d5;
        border-right: 1px solid #d5d5d5;
        border-top: 1px solid #d5d5d5;
        z-index: 9999999;
        position: absolute;
        padding: 10px;
        background: white;
        top: 67px;
        width: 97.5%;
        left: 9px;
      }
      .dropdown-container ul {
       margin: 0;
       padding: 0;
       }
     .dropdown-container ul li { list-style-type: none; }
     input[type="checkbox"] {
            position: relative;
            top: 2px;
        }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div>
    <label>States<span>*</span></label> 
    <div class="dropdown-container">
    <div class="dropdown-button noselect form-control">
        <div class="dropdown-label"></div>
        <div class="dropdown-quantity"><span class="quantity"></span></div>
        <span class="down-arrow">▼</span>
    </div>
    <div class="dropdown-list" style="display: none;">
        <input type="search" placeholder="Search states" class="dropdown-search">
        <ul id="pac">
          <li style="display: list-item;"><input value="Alabama " name="AL" type="checkbox"><label for="AL">Alabama</label></li>
          <li style="display: list-item;"><input value="Alaska" type="checkbox"><label for="AK">Alaska</label></li>
          <li style="display: none;"><input value="American Samoa" type="checkbox"><label for="AS">American Samoa</label></li>
          <li style="display: none;"><input value="AZ" type="checkbox"><label for="AZ">Arizona</label></li>
          <li style="display: none;"><input value="AR" type="checkbox"><label for="AR">Arkansas</label></li>
          <li style="display: list-item;"><input value="CA" type="checkbox"><label for="CA">California</label></li>
          <li style="display: none;"><input value="CO" type="checkbox"><label for="CO">Colorado</label></li>
          <li style="display: none;"><input value="CT" type="checkbox"><label for="CT">Connecticut</label></li>
        </ul>
    </div>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

关于标记和样式

  • <label>Hello world</label>这样的标签必须在未引用FormActionElement的情况下使用
  • 将复选框和标签文本包装到<label>中,以便两者都可单击
  • 使用.is-active.is-hidden CSS类来描述状态
  • 为箭头使用::before伪和content:,并使用.is-active(分配给组件下拉菜单)处理箭头状态
  • 将多个复选框用于相同的用途名称时,请使用名称属性,例如name="states[]",以便您可以捕获states数组中的所有选定值。
  • 使用data-*之类的data-name="Long name"属性来存储预览名称。
  • 使用CSS flex代替float s
  • 如果您打算生育孩子relative,请始终将父母置于absolute之类的位置

关于JavaScript

  • 通过使用.each()之类的jQuery的$dropdown.each(UI_dropdown); // Apply logic to all dropdowns来创建一个函数来处理所有自定义下拉菜单
  • 在该函数内部,始终引用一个子元素作为this下拉列表的子集,例如$('.dropdown-button', this);,以防止在DOM中定位每个单独的'.dropdown-button'
  • 确保向document添加处理程序以关闭活动下拉列表
  • 如果打开另一个下拉列表,请确保关闭下拉列表:

const $dropdown = $('.dropdown-container'); // Cache all;

function UI_dropdown() {

  const $this = $(this);
  const $btn = $('.dropdown-button', this);
  const $list = $('.dropdown-list', this);
  const $li = $('li', this);
  const $search = $('.dropdown-search', this);
  const $ckb = $(':checkbox', this);
  const $qty = $('.dropdown-quantity', this);


  $btn.on('click', function() {
    $dropdown.not($this).removeClass('is-active'); // Close other
    $this.toggleClass('is-active'); // Toggle this
  });

  $search.on('input', function() {
    const val = $(this).val().trim();
    const rgx = new RegExp(val, 'i');
    $li.each(function() {
      const name = $(this).text().trim();
      $(this).toggleClass('is-hidden', !rgx.test(name));
    });
  });

  $ckb.on('change', function() {
    const names = $ckb.get().filter(el => el.checked).map(el => {
      return `<span class="dropdown-sel">${el.dataset.name.trim()}</span>`;
    });
    $qty.html(names.join(''));
  });
}

$dropdown.each(UI_dropdown); // Apply logic to all dropdowns

// Dropdown - Close opened 
$(document).on('click', function(ev) {
  const $targ = $(ev.target).closest('.dropdown-container');
  if (!$targ.length) $dropdown.filter('.is-active').removeClass('is-active');
});
/* QuickReset */ * { margin: 0; box-sizing: border-box; }

.dropdown-container {
  position: relative;
}

.dropdown-label {
  padding: 4px 10px 4px 0;
}

.dropdown-label:before {
  content: "\25BC";
}

.dropdown-container.is-active .dropdown-label:before {
  content: "\25B2";
}

.dropdown-button {
  cursor: pointer;
  padding: 10px;
  border: 1px solid #d5d5d5;
  background: white;
  display: flex;
  flex-flow: row wrap;
}

.dropdown-quantity {
  flex: 1;
  display: flex;
  flex-flow: row wrap;
}

.dropdown-sel {
  display: inline-block;
  background: #eee;
  border-radius: 3em;
  padding: 2px 10px;
  margin: 0 3px 3px 0;
}

.dropdown-list {
  position: absolute;
  overflow-y: auto;
  z-index: 9999999;
  top: calc( 100% - 2px);
  width: 100%;
  max-height: 80vh;
  padding: 10px;
  padding-top: 0;
  border: 1px solid #d5d5d5;
  border-top: 0;
  background: white;
  display: none;
}

.dropdown-container.is-active .dropdown-list {
  display: block;
}

.dropdown-list input[type="search"] {
  padding: 5px;
  display: block;
  width: 100%;
}

.dropdown-list ul {
  padding: 0;
  padding-top: 10px;
  list-style: none;
}

.dropdown-list li {
  padding: 0.24em 0;
}

input[type="checkbox"] {
  margin-right: 5px;
}

/* HELPER CLASSES */
.noselect { user-select: none; }
.is-hidden { display: none; }
<div class="dropdown-container">
  <div class="dropdown-button noselect">
    <div class="dropdown-label">STATES:</div>
    <div class="dropdown-quantity"></div>
  </div>

  <div class="dropdown-list">
    <input type="search" placeholder="Search states" class="dropdown-search">
    <ul>
      <li>
        <label><input value="AL" name="states[]" data-name="Alabama" type="checkbox">Alabama</label>
      </li>
      <li>
        <label><input value="AK" name="states[]" data-name="Alaska" type="checkbox">Alaska</label>
      </li>
      <li>
        <label><input value="AS" name="states[]" data-name="American Samoa" type="checkbox">American Samoa</label>
      </li>
      <li>
        <label><input value="AZ" name="states[]" data-name="Arizona" type="checkbox">Arizona</label>
      </li>
      <li>
        <label><input value="AR" name="states[]" data-name="Arkansas" type="checkbox">Arkansas</label>
      </li>
      <li>
        <label><input value="CA" name="states[]" data-name="California" type="checkbox">California</label>
      </li>
      <li>
        <label><input value="CO" name="states[]" data-name="Colorado" type="checkbox">Colorado</label>
      </li>
      <li>
        <label><input value="CT" name="states[]" data-name="Connecticut" type="checkbox">Connecticut</label>
      </li>
    </ul>
  </div>
</div>


<div class="dropdown-container">
  <div class="dropdown-button noselect">
    <div class="dropdown-label">POSITIONS:</div>
    <div class="dropdown-quantity"></div>
  </div>
  <div class="dropdown-list">
    <input type="search" placeholder="Search positions" class="dropdown-search">
    <ul>
      <li>
        <label><input value="be" name="positions[]" data-name="Backend" type="checkbox">Backend</label>
      </li>
      <li>
        <label><input value="fr" name="positions[]" data-name="Frontend" type="checkbox">Frontend</label>
      </li>
      <li>
        <label><input value="hr" name="positions[]" data-name="HR" type="checkbox">HR</label>
      </li>
      <li>
        <label><input value="de" name="positions[]" data-name="Arizona" type="checkbox">Designer</label>
      </li>
    </ul>
  </div>
</div>

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

如果您想进一步优化代码,可以使用 prototype 代替 copy-distributed 函数,方法是创建 jQuery plugin 。如果您希望扩展功能,这样可以为您提供更好的组件封装和灵活的自定义选项。