Get the "original" (non-freezing) background color of the object when it hangs over it

I can get the background color of any element with the following functions:

$('.example').css('background') 

However, in my case, the mouse moves around this element, and I get a changed color due to the CSS :hover pseudo- :hover .

Is there any way to get the original color? Sort of

 $('.example').cssWithoutHover('background') 

You can test it here . Just put 5 in the last cell. The color of this cell will change after the animation.

+6
source share
6 answers

You can expand the original BG colors in the DOM and save them as data attributes.

 var board = $('#board-numbers'); board.children('div').each(function() { $(this).data('start-bg', $(this).css('background')); }); board.on('hover', 'div', function() { var curr_bg = $(this).css('background'); var start_bg = $(this).data('start-bg'); }); 
+5
source

Extending the idea posted by @vadim, I think I can go better. Just a clone() object, and don't put it in the DOM. that way it can't hang!

 css_color_without_hover_ = $('.example').clone(false).css('background'); 

There is no need to do a potentially expensive DOM scan when loading a document!

Anyhoo works well for me.

- EDIT -

I just noticed that there are limitations to this technique (or "gotchas").

If the element for which you are trying to get color data has its own color (or background color) inherited from the parent element, then the cloned object will not match the CSS template, which means that the style will not be applied to the jQuery object.

The workaround in this case is to clone the parent object (to which the corresponding style is applied) and extract its style, and not the child, instead.

+3
source

Almost certainly you cannot so easily.

Here are the derived solutions for this:

After loading the page, you can save the background color in a custom attribute (which will not change when you hover) to get it later:

 $().ready(function(){ $('.example').each(function(el){ $(this).data('bgcolor', $(this).css('background-color')); }); $('.example').hover(function(ev){ console.log($(this).data('bgcolor')); }); }): 
+2
source

you can use jss library. it gives you access to style sheet rules.

+1
source

I can suggest moving all background color definitions to different classes. And when you need a background color for a certain class, you can create an element "on the fly" and get its background color, and it will be absent: a modification of hovering. Something like that:

 $('<div class="normal-cell"></div>').css('background-color') 
+1
source

Another solution would be to use jQuery hover () to change the style on hover rather than pure CSS. For instance,

 $('.example').hover( function() { // handlerIn $(this).addClass('exampleHover'); }, function() { // handlerOut $(this).removeClass('exampleHover'); } ); 
0
source

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


All Articles