开发者

Change background color on elements with the same color

I'm trying to create a simple theme 开发者_Go百科system here. I have few elements with red background color. I also have a button that will change the elements background color to green.

I'm trying to code but I couldn't figure out how can I select and change the bg color of all red elements to green!

For example, I have 4 divs. Two of these have a red header, and when I click the button these headers background color must be changed to green. It's Ok here, but the problem is that the divs are dynamically generated, so do I have do loop all the page to find the red bg color? Could someone enlight me? =)

Thanks a lot! =)


I think the best solution would be to use different stylesheet for each theme and keep the current theme value in SESSION or COOKIE or just pass it as URL argument. But that would be a server side solution. On Client side, you can just use different classes for each theme and toggle them on the button push event using .toggleClass()

$('.green').toggleClass('red green');


The easiest way to do this would be to have a specific CSS class for each background color you're using. ex:

.color-red{ background-color: #FF0000; }
.color-green{ background-color: #00FF00; }

Once you do that you can select on the CSS class as well as set the CSS class:

$('#button-togreen').click(function(){
  $('.color-red').removeClass('color-red').addClass('color-green');
}

It's kind of a round-about way of doing it, however there is no easy way to select on a CSS attribute (to do that you'd have to select all elements of the page and then check each one of them for the background color attribute which would be scarily inefficient...)


I don't know what you mean by headers, but I think this should do what you want:

$('.myDivs').filter(function(index){
  return $(this).css('color') == 'red';
}).css('color', 'green');
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜