简体   繁体   English

更改所选选项的颜色 - jQuery

[英]Change color of option selected - jQuery

I want to change the text color of the option that is selected="selected": 我想更改所选选项=“已选择”的文本颜色:

    <select class="select">
        <option value="--">--</option>
        <option value="2014">2014</option>
        <option value="2013">2013</option>
        <option value="2012" selected="selected">2012</option>
        <option value="2011">2011</option>
    </select>

I have been trying with CSS but it seems its not possible: 我一直在尝试CSS,但似乎不可能:

    .select select [selected="selected"]{
        color: #2b2b2b;
    }

Any ideas with jQuery? 有关jQuery的任何想法吗?

I have been trying with CSS but it seems its not possible: 我一直在尝试CSS,但似乎不可能:

Because you are targetting the select tag and not option tag also, that selector means select any select element nested inside element having .select class 因为您还要定位select标签而不是option标签,所以选择器意味着选择嵌套在具有.select class元素内的任何select元素

select option[selected] {
    color: red;
}

Demo 演示

You are using class so you can make a selector like 您正在使用class因此您可以创建一个选择器

.select option[selected] {
   color: red;
}

Try 尝试

$('.select').change(function () {
            $(this).find('option:selected').css('background-color', 'red');
});

for changing color of text Use 用于更改文本颜色使用

  $(this).find('option:selected').css('color', 'red'); 

FIDDLE 小提琴

LIke this 像这样

demo 演示

js JS

    $('.select').change(function () {
    $(this).find('option').css('color', '#000000');
    $(this).find('option:selected').css('color', '#ff0000');
}).trigger('change');

You can do: 你可以做:

 $('.select option:selected').css('color','#2b2b2b');

or if you want to fire the event every time select option has been changed, you can do: 或者如果您想在每次更改select选项时触发事件,您可以执行以下操作:

$('.select').change(function () {
     $(this).find('option:selected').css('color','#2b2b2b');
});

or with just plain css: 或者只是普通的CSS:

select option:checked {
     color: #2b2b2b;
}
.select option:checked {
    color: red;
}

Not sure about browser compatibility on this one.. 不确定这个浏览器的兼容性..

Edit: https://developer.mozilla.org/en-US/docs/Web/CSS/:checked 编辑: https//developer.mozilla.org/en-US/docs/Web/CSS/check

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM