萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 模擬 Select 下拉框(支援搜尋過濾、鍵盤操作)

原生 <select> 樣式難控制,常需用 <div>+<ul> 模擬。本文提供含搜尋過濾、鍵盤導航、多實例隔離的完整組件雛形。

核心邏輯

function showExpand(inputId, listId, listClass) {
  // 關閉其他同類下拉
  if (listClass) $('.' + listClass).hide();
  var $input = $('#' + inputId);
  var $list = $('#' + listId);
  // 定位:輸入框下方
  var rect = $input[0].getBoundingClientRect();
  $list.css({ left: rect.left + 'px', top: rect.bottom + 'px' }).show();
  // 選項點擊賦值
  $list.find('li').off('click').on('click', function() {
    $input.val($(this).text()).focus();
    $list.hide();
  });
}

function filterList(inputId, listId) {
  var $input = $('#' + inputId);
  var $list = $('#' + listId);
  var kw = $input.val().toUpperCase();
  $list.find('a').each(function() {
    var $li = $(this).parent();
    $(this).text().toUpperCase().indexOf(kw) === -1 ? $li.hide() : $li.show();
  });
}

綁定事件

$('#txt_city').on('focus', function() { showExpand('txt_city', 'city_select1', 'expand'); })
             .on('keyup', function() { filterList('txt_city', 'city_select1'); });

$('#txt_city2').on('focus', function() { showExpand('txt_city2', 'city_select2', 'expand'); })
              .on('keyup', function() { filterList('txt_city2', 'city_select2'); });

HTML 結構

<input type="text" id="txt_city" class="input_expand">
<a href="#" onclick="showExpand('txt_city','city_select1','expand')">▼</a>
<div class="expand" id="city_select1">
  <ul>
    <li><a href="#">SH 上海</a></li>
    <li><a href="#">BJ 北京</a></li>
    <li><a href="#">HZ 杭州</a></li>
  </ul>
</div>

CSS 要點

.expand { display:none; position:absolute; width:200px; max-height:150px; overflow-y:auto; border:1px solid #ccc; background:#fff; z-index:100; }
.expand li { margin:1px 0; }
.expand a { display:block; padding:2px 8px; text-decoration:none; }
.expand a:hover { background:#ff9; }

無障礙補充

  • 添加 role="combobox"、aria-expanded、aria-controls。
  • 支援 Enter/Esc/↑↓ 鍵盤操作。
copyright © 萬盛學電腦網 all rights reserved