前言
Select2.js 原本的搜尋框沒有任何輔助文字,如果沒有嘗試輸入文字就很容易忽略掉它,後來在網路上找到 andreivictor 提供的資源,加段 JavaScript 描述文字( placeholder )就蹦出來了,可以更直覺引導使用者去操作,如果你也有這類需求,那就繼續看下去吧!
JavaScript
(function($) {
var Defaults = $.fn.select2.amd.require('select2/defaults');
$.extend(Defaults.defaults, {
searchInputPlaceholder: ''
});
var SearchDropdown = $.fn.select2.amd.require('select2/dropdown/search');
var _renderSearchDropdown = SearchDropdown.prototype.render;
SearchDropdown.prototype.render = function(decorated) {
// invoke parent method
var $rendered = _renderSearchDropdown.apply(this, Array.prototype.slice.apply(arguments));
this.$search.attr('placeholder', this.options.get('searchInputPlaceholder'));
return $rendered;
};
})(window.jQuery);
$(function () {
$(".select2").select2({
// options
searchInputPlaceholder: '輸入關鍵字搜尋...'
});
});
CSS
我在右邊加上了放大鏡的圖示,更能直覺了解這是個搜尋框(但前提是網站剛好有引入 Font Awesome )。
.select2-search--dropdown {position: relative;}
.select2-search--dropdown::after {
content: "\f002";
position: absolute;
right: 25px;
top: 17px;
z-index: -1;
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-family: 'FontAwesome' !important;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
opacity: .4;
}