微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jquery – 如何动态更改元素的颜色?

如何使用变量更改元素的颜色?

假设我们有四个字符串(颜色).我需要给每个类元素赋予不同的1,2,3,4,1,3 ……等等:

function pressLineColors() {

    var a = "#eee",b = "#123",c = "#fff",d = "#ae23e5";

     $('.pressLine').each(function (i) {
         //go througt each of this,and give them colors,so when new elements
        // appear,give them next color. 
     });
}

一个元素sholud有颜色a,第二个b,第三个c,第四个d和第五个a,……

解决方法

function pressLineColors() {

    //setup array of colors and a variable to store the current index
    var colors = ["#eee","#123","#fff","#ae23e5"],curr   = 0;

    //loop through each of the selected elements
    $.each($('.pressLine'),function (index,element) {

        //change the color of this element
        $(this).css('color',colors[curr]);

        //increment the current index
        curr++;

        //if the next index is greater than then number of colors then reset to zero
        if (curr == colors.length) {
            curr = 0;
        }
    });
}

这是一个演示:http://jsfiddle.net/SngJK/

更新

您还可以使用此答案的注释中的建议来缩短代码

function pressLineColors() {
    var colors = ["#eee",len    = colors.length;
    $.each($('.pressLine'),element) {
        $(this).css('color',colors[index % len]);
    });
}

这是一个演示:http://jsfiddle.net/SngJK/2/

更新

您还可以使用.css(‘color’,function(){})迭代每个元素,返回您想要生成元素的颜色:

$('.pressLine').css('color',style) {
    return colors[index % len];
});

这是一个演示:http://jsfiddle.net/SngJK/4/

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐