JS註冊組|在Select2套件的搜尋框加上描述文字


Posted by itiswonderfall on 2022-02-18

前言

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;
}

 


 

資料來源

How make select2 placeholder for search input


#js #JS註冊組 #javascript #css #placeholder







Related Posts

[TensorFlow Certification Day10] Time Series Completed (6hrs)

[TensorFlow Certification Day10] Time Series Completed (6hrs)

[筆記] Jest

[筆記] Jest

MTR04_0622

MTR04_0622


Comments