开发者

Set Background color for a selected item in a Select option (multiple) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.

开发者_开发问答

Closed 9 years ago.

Improve this question

I'm trying to change the background color of the selected items in a listbox (select multiple options).

I tried with css... I tried with JavaScript... and with jquery... I really don't know what happen!! But I'm unable to find the answer :_(.

I read at least 10 questions in this forum.. and I tried all the proposed solutions but I only can change the background of the complete list... not the selected items. The only way I found is to use an unordered list with clickable list items instead if my select - option ... but I'm working with a form, and I want to send to the server the selected items in the traditional way.


This will change the background color of the selected option

$('select').change(function() {
    $('option').css('background', 'none');
    $('option:selected').css('backgroundColor', 'red');
}).change();

Check working example at http://jsfiddle.net/TxbVt/1/


Doesn't look like it wants to play ball:

<style>

::selection {
   background: #FF0000; /* Safari */
   }
::-moz-selection {
   background: #FF0000; /* Firefox */
}
</style>

<select multiple="true">
<option><span style="background:FF0000;">One</span></option>
<option>Two</option>
<option>Three</option>
</select>

<p>This is text.</p>

This doesn't suprise me. In my experience widgets are generally resistant to such styling. Rolling your own, like in Hussein's approach, looks like your only way out.


JavaScript

document.getElementById('your-select').onchange = function() {

    var options = this.getElementsByTagName('option'),
        selectedClassName = 'selected';

    for (var i = 0, length = options.length; i < length; i++) {
        var option = options[i],
            className = option.className;

        if (i == this.selectedIndex) {
            option.className += selectedClassName;
        } else {
            option.className = (' ' + className + ' ').replace(new RegExp('\\s' + selectedClassName + '\\s'), '');
        }
    }
};

jsFiddle.

CSS

#your-select option.selected {
    background: red;   
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜