萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

Div+CSS+jQuery 模擬 Select 下拉選單:美化與表單傳值完整實作

原生 <select> 樣式難以自訂(尤其是箭頭、下拉面板)。業界通用做法:用 <div> + <ul> 模擬視覺,隱藏 <input type="hidden"> 存儲實際值提交表單。本文提供完整的 jQuery 插件封裝、HTML 結構、CSS 樣式、無障礙增強與現代化重構建議。

核心架構

<form>
  <div id="divselect" class="custom-select">
    <span class="select-trigger" aria-haspopup="listbox" aria-expanded="false" tabindex="0">
      <span class="select-value">請選擇分類</span>
      <span class="select-arrow" aria-hidden="true">▼</span>
    &span>
    <ul class="select-options" role="listbox" hidden>
      <li role="option" data-value="1"><a href="javascript:;">導航菜單</a></li>
      <li role="option" data-value="2"><a href="javascript:;">下拉特效</a></li>
      <li role="option" data-value="3"><a href="javascript:;">Select 模擬</a></li>
      <li role="option" data-value="4"><a href="javascript:;">特效代碼</a></li>
      <li role="option" data-value="5"><a href="javascript:;">jQuery 下拉菜單</a></li>
    </ul>
  </div>
  <input type="hidden" name="category" id="inputselect" value="">
</form>

jQuery 插件:支援鍵盤、無障礙、多實例

(function($) {
  $.fn.divselect = function(inputSelector) {
    return this.each(function() {
      const $select = $(this);
      const $input = $(inputSelector);
      const $trigger = $select.find('.select-trigger');
      const $options = $select.find('.select-options');
      const $items = $options.find('[role="option"]');
      
      // 開關下拉
      const toggle = (open) => {
        $options.attr('hidden', !open);
        $trigger.attr('aria-expanded', open);
        $select.toggleClass('open', open);
      };
      
      $trigger.on('click keydown', (e) => {
        if (e.type === 'click' || e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          toggle(!$options.is(':visible'));
        } else if (e.key === 'Escape') {
          toggle(false);
        }
      });
      
      // 選項點擊/鍵盤選擇
      $items.on('click keydown', 'a', function(e) {
        if (e.type === 'click' || e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          const $opt = $(this).closest('[role="option"]');
          const text = $opt.text().trim();
          const value = $opt.data('value');
          
          $trigger.find('.select-value').text(text);
          $input.val(value).trigger('change'); // 觸發表單驗證
          toggle(false);
        } else if (e.key === 'ArrowDown') {
          e.preventDefault();
          focusNext($items, $items.index($(this).closest('[role="option"]')));
        } else if (e.key === 'ArrowUp') {
          e.preventDefault();
          focusPrev($items, $items.index($(this).closest('[role="option"]')));
        }
      });
      
      // 點擊外部關閉
      $(document).on('click.divselect', (e) => {
        if (!$select.is(e.target) && $select.has(e.target).length === 0) {
          toggle(false);
        }
      });
      
      // 鍵盤導航輔助
      function focusNext($list, index) { const next = $list.eq((index + 1) % $list.length); next.find('a').trigger('focus'); }
      function focusPrev($list, index) { const prev = $list.eq((index - 1 + $list.length) % $list.length); prev.find('a').trigger('focus'); }
    });
  };
})(jQuery);

// 初始化
$(function() {
  $('#divselect').divselect('#inputselect');
});

CSS 樣式:美化與狀態管理

.custom-select {
  position: relative;
  display: inline-block;
  width: 100%;
  max-width: 300px;
  font-family: inherit;
  font-size: 14px;
}
.select-trigger {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  background: #fff;
  cursor: pointer;
  transition: border-color 0.2s, box-shadow 0.2s;
}
.select-trigger:hover { border-color: #aaa; }
.select-trigger:focus { outline: none; border-color: #007bff; box-shadow: 0 0 0 3px rgba(0,123,255,0.25); }
.select-arrow { transition: transform 0.2s; }
.custom-select.open .select-arrow { transform: rotate(180deg); }

.select-options {
  position: absolute;
  top: 100%; left: 0; right: 0;
  margin: 4px 0 0;
  padding: 0;
  list-style: none;
  border: 1px solid #ddd;
  border-radius: 6px;
  background: #fff;
  box-shadow: 0 8px 24px rgba(0,0,0,0.12);
  max-height: 240px;
  overflow-y: auto;
  z-index: 100;
}
.select-options[hidden] { display: none; }
.select-options li { padding: 0; }
.select-options a {
  display: block;
  padding: 10px 12px;
  color: #333;
  text-decoration: none;
  transition: background 0.1s;
}
.select-options a:hover,
.select-options a:focus { background: #f0f7ff; color: #007bff; outline: none; }
.select-options [aria-selected="true"] a { background: #e7f1ff; font-weight: 500; }

無障礙 (a11y) 關鍵點

  • role="listbox"、role="option"、aria-haspopup、aria-expanded:語意化給螢幕閱讀器
  • tabindex="0" 讓觸發器可聚焦
  • 鍵盤操作:Enter/Space 開關、↑↓ 選擇、Esc 關閉、Tab 移出關閉
  • hidden 屬性控制可見性(比 display:none 語意更好)

現代化重構方向(無 jQuery、原生 Web Components)

// Vanilla JS 類別版
class CustomSelect extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
    this.shadowRoot.innerHTML = `...`; // 樣式+結構
    this.$trigger = this.shadowRoot.querySelector('.select-trigger');
    this.$options = this.shadowRoot.querySelector('.select-options');
    this.$input = this.querySelector('input[type="hidden"]') || this._createHiddenInput();
    this._bindEvents();
  }
  // ... 同邏輯
}
customElements.define('custom-select', CustomSelect);

// 使用
<custom-select name="category">
  <option value="1">導航菜單</option>
  <option value="2">下拉特效</option>
  ...
</custom-select>

已知限制與替代庫推薦

  • 大量選項(>100):虛擬滾動、搜尋過濾 → 推薦 Choices.js、Tom Select、Select2 (jQuery)
  • 多選、分組、遠端搜尋 → 推薦 Selectize、React Select、Vue Select
  • 原生 <select> 現代化:appearance: none + 背景圖箭頭 + <datalist> 組合,輕量無依賴

結語:模擬 Select 是前端經典課題。理解「視覺層 + 隱藏表單字段」雙層架構、無障礙屬性、鍵盤交互、點擊外部關閉等細節,是打造高質量表單組件的基礎。新專案優先考慮無依賴原生實現或成熟無障礙庫。

copyright © 萬盛學電腦網 all rights reserved