原本處理tags輸入控件是不少的,好比select2,又好比chosen,都各有各的好處,但也各有各的不足。今天選擇一款簡單的插件:selectize.js Github: https://github.com/selectize/...。javascript
Selectize.js特色就是容易用,來看看怎麼用。css
引入項目文件html
<link href="https://cdn.bootcss.com/selectize.js/0.12.4/css/selectize.min.css" rel="stylesheet"> <link href="https://cdn.bootcss.com/selectize.js/0.12.4/css/selectize.bootstrap3.min.css" rel="stylesheet"> <script src="https://cdn.bootcss.com/selectize.js/0.12.4/js/standalone/selectize.min.js"></script>
selectize.bootstrap3.min.css
不是必須的,並且尚未原生的ui那麼漂亮,但勝在和bootstrap風格統一。java
初始化更簡單git
<input type="text" id="input-tags" /> $('#input-tags').selectize({ delimiter: ',', persist: false, create: function(input) { return { value: input, text: input } } });
這隻能輸入簡單的tag,複雜一點的就徹底無濟於事,要想實現上圖那種複雜佈局的tag,而且可以加載遠程服務器上的數據,還得花點時間配置一下選項。github
$('#games').selectize({ options: [], create: false, valueField: 'id', labelField: 'title', searchField: 'title', maxItems: 5, render: { option: function(item, escape) { var tags = []; for (var i = 0, n = item.tags.length; i < n; i++) { tags.push('<span class="label label-default">' + escape(item.tags[i]) + '</span>'); } return '<div>' + '<div class="pull-left"><img src="' + escape(item.avatar) + '" style="max-width: 50px" alt=""></div>' + '<div class="title pull-left" style="padding-left: 5px">' + '<div><strong class="name">' + escape(item.title) + '</strong></div>' + '<span class="label label-info">' + escape(item.category) + '</span>' + '<div class="tags">' + (tags.length ? tags.join(' ') : '沒有標籤') + '</div>' + '</div>' + '</div>'; } }, load: function(query, callback) { if (!query.length) return callback(); $.ajax({ url: "{{ url('games/query') }}", type: 'GET', dataType: 'json', data: { term: query, limit: 4 }, error: function() { callback(); }, success: function(res) { callback(res.results); } }); } });