使用jquery为选择框中的选项文本提供样式

时间:2018-03-04 13:04:45

标签: php jquery html css twitter-bootstrap

我在选择框中有一个选项。我需要设置特定文本的样式,使文本证明选项合理。我正在使用php,bootstrap和jquery。

这是我的代码:

reset

 <option style="margin:5px 5px;"value="<?php echo $totvalue['ID']; ?>" data-position="<?php echo $i;?>"><?php                 
                    echo $totvalue['Abbreviation'].' - '.$quotation.' - '.$totvalue['Name'].' - '.$totvalue['Category']; ?></option>

我需要<option style="margin:5px 5px;" value=1002>TAKAJ - A - SAMSUUNG - 4G</option> <option style="margin:5px 5px;" value=1003>YEG - L - SONY - 3G</option> - A -选项位于- L -。如何使用jquery实现这一点..

1 个答案:

答案 0 :(得分:0)

选择输入中的选项由浏览器生成。你不能在那里添加风格。 options in bootstrap

但你可以在jQuery中创建自己的select:

// Iterate over each select element
$('select').each(function () {

    // Cache the number of options
    var $this = $(this),
        numberOfOptions = $(this).children('option').length;

    // Hides the select element
    $this.addClass('s-hidden');

    // Wrap the select element in a div
    $this.wrap('<div class="select"></div>');

    // Insert a styled div to sit over the top of the hidden select element
    $this.after('<div class="styledSelect"></div>');

    // Cache the styled div
    var $styledSelect = $this.next('div.styledSelect');

    // Show the first select option in the styled div
    $styledSelect.text($this.children('option').eq(0).text());

    // Insert an unordered list after the styled div and also cache the list
    var $list = $('<ul />', {
        'class': 'options'
    }).insertAfter($styledSelect);

    // Insert a list item into the unordered list for each select option
    for (var i = 0; i < numberOfOptions; i++) {
        $('<li />', {
            text: $this.children('option').eq(i).text(),
            rel: $this.children('option').eq(i).val()
        }).appendTo($list);
    }

    // Cache the list items
    var $listItems = $list.children('li');

    // Show the unordered list when the styled div is clicked (also hides it if the div is clicked again)
    $styledSelect.click(function (e) {
        e.stopPropagation();
        $('div.styledSelect.active').each(function () {
            $(this).removeClass('active').next('ul.options').hide();
        });
        $(this).toggleClass('active').next('ul.options').toggle();
    });

    // Hides the unordered list when a list item is clicked and updates the styled div to show the selected list item
    // Updates the select element to have the value of the equivalent option
    $listItems.click(function (e) {
        e.stopPropagation();
        $styledSelect.text($(this).text()).removeClass('active');
        $this.val($(this).attr('rel'));
        $list.hide();
        /* alert($this.val()); Uncomment this for demonstration! */
    });

    // Hides the unordered list when clicking outside of it
    $(document).click(function () {
        $styledSelect.removeClass('active');
        $list.hide();
    });

});

See on jsFiddle