JQuery freezes every background color

How to hover all different background-color ? This code sets the background color:

 var dlcabgColors = [ 'rgb(233, 147, 26)', 'rgb(22, 145, 190)', 'rgb(22, 107, 162)' , 'rgb(27, 54, 71)' ]; var i = 0; $('.abc').each(function() { $(this).css('background-color', dlcabgColors[i]); i = (i + 1) % dlcabgColors.length; }); 

But when I add the hover function, the function will repeat the entire background color.

I want to specify elements of the specified color, and not repeat the entire background color

Scenario

As always, your help is appreciated!

Thanks to everyone!)

+4
source share
2 answers

Is this what you want?
LIVE DEMO Depending on the 0f index, the hover changes color according to the position of the array:

 var dlC = [ 'rgb(233, 147, 26)', 'rgb(22, 145, 190)', 'rgb(22, 107, 162)', 'rgb(27, 54, 71)' ]; var dlH= [ '#000', /* only difference... why that? */ 'rgb(22, 145, 190)', 'rgb(22, 107, 162)', 'rgb(27, 54, 71)' ]; $('.abc').each(function( i ) { $(this).css({backgroundColor : dlC[i] }) .on("mouseenter mouseleave",function( e ) { $(this).css({backgroundColor : e.type=="mouseenter" ? dlH[i] : dlC[i] }); }); }); 

the ? : ? : I used the ternary operator. You can use Goog for it if you do not know how logic works.

+3
source

You should only do this with CSS, the only thing you need is to create the appropriate classes for it and then add them to your elements. i.e:.

 var totalColors = 4; $('.abc').each(function(i, e) { $(this).addClass("color"+i%totalColors); }); .color1:hover { background: #0FF } .color2:hover { background: #FF0 } .color3:hover { background: #0F0 } .color0:hover { background: #F00 } 

Edit: minor fix and here is the fiddle: http://jsfiddle.net/CxmGp/

Edit2: you can also generate css classes directly through javascript: How to dynamically create a CSS class in JavaScript and apply?

+3
source

Source: https://habr.com/ru/post/1483942/


All Articles