How to change the css of color of select2 tags?

后端 未结 8 1891
萌比男神i
萌比男神i 2020-12-31 06:47

I just started using project for showing multiple tags from a select box and it works great, thanks for the library.

I just need to modify the color or css of the ta

8条回答
  •  难免孤独
    2020-12-31 07:27

    In my case I needed to show the difference between tags that were "selected" and those which were being added.

    The help here was for the previous versions of select2, and not of much use. Using the current 4.0 version (with its terribly sparse documentation) I was able to achieve this using the template functions and a little bit of 'cleverness'.

    First step is to template the results (it should be noted that on every select or remove action this is fired for every selection in the box). This normally returns JUST the text that will go in the resulting LI... however we want to wrap that text in a span (and tell S2 not to strip the HTML out by returning an object) with a custom CSS class for our type. In my example I use the selected property to determine this:

    $('.select2_sortable').select2({
        tags: true,
        templateSelection: function(selection) {
            if(selection.selected) {
                return $.parseHTML('' + selection.text + '');
            }
            else {
                return $.parseHTML('' + selection.text + '');
            }
        }
    });
    

    Your resulting HTML after an item is selected should be something like this:

    • × John Doe
    • × fdfsdfds

    But this isn't enough, as we need to access the parent LI, not the span child. And since CSS doesn't allow for parent selectors, we have to run some jQuery to make it happen. Because these are redrawn we'll want to run this function on both the select and remove events of the Select2 item:

    $('.select2_sortable').on("select2:select", function (ev) {
        updateSelectedParents();
    });
    $('.select2_sortable').on("select2:removed", function (ev) {
        updateSelectedParents();
    });
    
    function updateSelectedParents() {
        $('.im_selected').closest('li').addClass('im_connected_item');
        $('.im_writein').closest('li').addClass('im_writein_item');
    }
    

    Finally resulting in:

    • × John Doe
    • × fdfsdfds

    And allowing you to style your elements based on the im_writein_item and im_connected_item CSS classes.

提交回复
热议问题