要求實現一個輕量級的在客戶端篩選的combobox,支持大數據量(超過1000個items),能快速檢索內容,並支持數據的設置和活動等基本操作。在這之前嘗試過使用Jquery UI的Autocomplete,但是當數據量太大時客戶端檢索速度太慢(甚至會導致瀏覽器卡死)。索性乾脆基於JQuery自己寫 ...
要求實現一個輕量級的在客戶端篩選的combobox,支持大數據量(超過1000個items),能快速檢索內容,並支持數據的設置和活動等基本操作。在這之前嘗試過使用Jquery UI的Autocomplete,但是當數據量太大時客戶端檢索速度太慢(甚至會導致瀏覽器卡死)。索性乾脆基於JQuery自己寫一個吧!
所依賴的庫:
CSS:
body { font-size: 14px; font-family: "microsoft yahei", Verdana, Arial, sans-serif, "Times New Roman"; max-width: 500px; margin: 0 auto; -webkit-text-size-adjust: none; } .combobox-menu { background-color: #fff; border: 1px solid #ccc; min-height: 100px; overflow-y: auto; font-size: 0.875rem; padding: 0; } .combobox-menu li { list-style: none; padding: .625em 1em; cursor: pointer; } .combobox-menu li.selected { background-color: #337ab7; color: #fff; } .combobox-menu li.normal:hover { background-color: #d9edf7; } .combobox-menu-dropdown { position: absolute; z-index: 1000; -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175); box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175); } .combobox-menu-caret { display: inline-block; width: 0; height: 0; margin-left: 2px; vertical-align: middle; border-top: 4px dashed; border-right: 4px solid transparent; border-left: 4px solid transparent; position: absolute; right: 8px; top: 50%; }
JavaScript:
/* event wrapper */ var eventWrapper = function () { this.init(); }; eventWrapper.prototype.init = function () { this.events = {}; }; eventWrapper.prototype.on = function (key, func) { if (func instanceof Function) { if (!this.events[key]) { this.events[key] = [func]; } else { this.events[key].push(func); } return this; } }; eventWrapper.prototype.emmit = function (key) { if (this.events[key]) { var _list = this.events[key]; var that = this; var args = arguments; [].shift.apply(args); for (var i = 0, ci; ci = _list[i]; i++) { ci.apply(that, args); } } }; eventWrapper.prototype.remove = function (key) { delete this.events[key]; }; /*********************/ /* combobox控制項 */ var comboBox = function (element, options) { var def = { menuStyle: {maxHeight: 180}, readonly: false, data: [] }; this.opts = $.extend(true, def, options); var that = this; this.event = new eventWrapper(); this.source = []; this.selected = null; this.$source = $(element); if (this.opts.readonly) { this.$source.attr('readonly', 'readonly'); } this.$source.on('input paste', function () { that.changeText($(this)); }); this.$container = $('<div style="position:relative;"></div>'); // this.$caret = $('<span class="combobox-menu-caret"></span>'); this.$menu = $('<ul class="combobox-menu"></ul>'); this.$lis = null; this.$menu.on('click', 'li', function () { if (!that.opts.readonly) { that.select($(this).attr('data-value')); } }); this.init(); }; comboBox.prototype.init = function () { if (this.opts.data && this.opts.data.length > 0) { this.$source.after(this.$menu); // this.render(this.opts.data); this.$menu.css('minWidth', this.$source.outerWidth()); this.$lis = this.$menu.find('li'); this.setMenuStyle(); var that = this; this.$menu.addClass('combobox-menu-dropdown').hide(); this.$source.wrap(that.$container); // this.$caret.insertAfter(that.$source); if (!this.opts.readonly) { that.$source.on('click', function () { if ($(this).val().trim().length === 0) return; that.expandMenu(that); }); // 添加關閉下拉列表事件 $(document).click(function (e) { var target = e.target; if (!$(target).is(that.$source) && !$(target).parents().is(that.$menu)) { that.$menu.hide(); if (that.getSelected() && that.$source.val().trim().length === 0) { that.select(that.getSelected().val); } } }); } } }; comboBox.prototype.render = function (data) { for (var i = 0, ci; ci = data[i]; i++) { var _item = $('<li></li>'); _item.attr('data-value', ci.val); _item.text(ci.txt); if (ci.selected) { this.selected = ci; } this.$menu.append(_item); } }; comboBox.prototype.update = function (data) { this.$menu.empty(); if (data) { this.render(data); } }; comboBox.prototype.expandMenu = function () { if (this.$menu.is(':hidden')) { this.$menu.show(); } }; comboBox.prototype.setMenuStyle = function () { if (this.opts.menuStyle) { this.$menu.css(this.opts.menuStyle); } }; comboBox.prototype.select = function (val) { if (!val) return; var item = _.find(this.opts.data, {val: val}); if (item) { this.selected = item; this.update([this.selected]); this.$source.val(item.txt); this.$source.attr('data-value', item.val); this.$menu.hide(); this.event.emmit('change', item); } }; comboBox.prototype.changeText = function (item) { var _data = null; this.expandMenu(); var _txt = item.val(); if ($.trim(_txt).length > 0) { var reg = new RegExp(_txt, 'i'); _data =_.filter(this.opts.data, function (o) { return reg.test(o.txt); }); } this.update(_data); }; comboBox.prototype.getSelected = function () { return this.selected; }; comboBox.prototype.setSelected = function (val) { this.select(val); }; comboBox.prototype.onChange = function (fn) { this.on('change', fn); }; comboBox.prototype.on = function (key, fn) { this.event.on(key, fn); };
HTML:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>comboBox</title> <link rel="stylesheet" href="bootstrap.min.css"/> <link rel="stylesheet" href="style.css"/> <script src="jquery.min.js"></script> <script src="underscore-min.js"></script> <script src="comboBox.js"></script> </head> <body> <form> <div class="form-group"> <label for="sel_mct">選擇項:</label> <input type="text" class="form-control" value="" id="sel_mct" placeholder="輸入名稱過濾"> <input type="hidden" id="mct" name="mct"/> </div> </form> <script type="text/javascript"> $(function () { var _combox = new comboBox($('#sel_mct'), { menuStyle: {textAlign: 'left'}, data: [ {val: '1', txt: 'Microsoft'}, {val: '2', txt: 'Google'}, {val: '3', txt: 'Facebook'}, {val: '4', txt: 'Twitter'}, {val: '5', txt: 'Apple Inc.'}, {val: '6', txt: 'Amazon.cn'}, {val: '7', txt: 'Adobe'}, {val: '8', txt: 'Oracle'}, {val: '9', txt: 'LinkedIn'}, {val: '10', txt: 'Alibaba'} ] }); _combox.on('change', function () { $('#mct').val(_combox.getSelected().val); }); _combox.setSelected('2'); }); </script> </body> </html>
主要方法:
- comboBox構造函數,接受一個JQuery對象作為宿主HTML元素,該元素為頁面上的input標簽。另外一個參數指定comboBox的配置項,包括:
- menuStyle:指定下拉框的樣式,預設樣式有maxHeight: 180. 所有樣式均以JQuery css的方式進行指定。
- readonly:Boolean類型,是否為只讀。
- data:指定數據源。數據源為JSON數組,其中每一個元素是帶有val和txt屬性的JSON,val表示item的值,txt表示item的顯示文本。
- setSelected,用於在comboBox初始化完畢之後,設置預設選中的元素。接受一個字元串變數,用於表示選中item的值。
- getSelected,獲取選中的item,將返回一個JSON對象,包含val和txt屬性。
- onChange事件,當comboBox中的item被選中時觸發。
完整示例下載:comboBox.zip
另外推薦一個好用的select控制項,功能很強大!