Replace everytime this color by that color in css with jquery

后端 未结 1 999
隐瞒了意图╮
隐瞒了意图╮ 2021-01-02 00:35

I have a lot of divs, some of them have a background-color: #aaa, others have font color: #aaa, and others border-color: #aaa

相关标签:
1条回答
  • 2021-01-02 01:14

    You want to iterate over all the elements of the type you want (in this case I picked div since it’s super common) and assign the color dynamically like so:

    HTML:

    <div id="one">Some text</div>
    <div id="two">Some text</div>
    <div id="three">Some text</div>
    <div id="four">Some text</div>
    <div id="change">
        <input type="button" value="Change Colors!" />
    </div>
    

    JQuery:

    $("#change").click(function () {
        $("div").each(function () {
            var color = $(this).css("color");
            if (color == "rgb(170, 170, 170)") {
                $(this).css("color", "#ccc");
            }
        });
    });
    

    NOTE: JQuery .css() returns an RGB color value like rgb(r, g, b) so you need to convert the returned RGB value to a HEX value. This can be done programatically but is outside the scope of this question.

    CSS:

    #one, #two {
        color: #aaa;
    }
    #three, #four {
        color: green;
    }
    

    Here is the JSFiddle:

    http://jsfiddle.net/hQkk3/44/

    0 讨论(0)
提交回复
热议问题