FancySelect 是一款小巧實用的 jQuery 下拉框美化外掛,採用時尚的扁平化設計風格,是追求簡約美感的開發者的理想選擇之一。它可以與 jQuery 或 Zepto 搭配使用,讓原本樸素的原生下拉框煥然一新。本文將詳細介紹它的使用方法與各項進階功能。
FancySelect 的使用非常簡單。只要在頁面中放置 <select> 下拉框元件,然後透過 .fancySelect() 方法呼叫即可。若某個選項沒有值,外掛會以某種佔位文字來代替它。
<select class="basic">
<option value="">Select something…</option>
<option>Lorem</option>
<option>Ipsum</option>
<option>Dolor</option>
<option>Sit</option>
<option>Amet</option>
</select>
$('.basic').fancySelect();
預設情況下,FancySelect 在 iOS 裝置上僅使用原生的下拉框與樣式。若想覆蓋這個行為,可以在初始化時將 forceiOS 設為 true。此外,你也可以透過 <select> 元素的 data-class 屬性來指定不同樣式的下拉框。
如果下拉框的 options 在外掛初始化後被修改了,你可以觸發 update.fs 事件來通知外掛更新選項列表:
var mySelect = $('.my-select');
mySelect.fancySelect();
mySelect.append('<option>New Option</option>');
mySelect.trigger('update.fs');
FancySelect 會在初始化後自動處理 disabled 狀態。若需要重新設定,可以使用 enable.fs 或 disable.fs 事件:
var mySelect = $('.my-select');
mySelect.fancySelect(); // 因 HTML 屬性而處於停用狀態
mySelect.trigger('enable.fs'); // 現在已啟用
mySelect.trigger('disable.fs'); // 再次停用
若想做個性化的呈現效果,可以使用 optionTemplate 方法,它會透過 option 選項返回一段 HTML 字串:
<select class="bulbs">
<option data-icon="old">Incandescent</option>
<option data-icon="curly">CFL</option>
<option data-icon="work">Halogen</option>
</select>
$('.bulbs').fancySelect({
optionTemplate: function(optionEl) {
return optionEl.text() + '<br>';
}
});
你可以在 <select> 選項改變時監聽 change.fs 事件,進而觸發 DOM 原生的 change 事件:
var mySelect = $('.my-select');
mySelect.fancySelect().on('change.fs', function() {
$(this).trigger('change.$');
});
透過這些功能,FancySelect 能讓你在保留原生下拉框行為的同時,享受更精緻美觀的使用者介面。